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
|
@@ -0,0 +1,1331 @@
|
|
|
1
|
+
"""LLM execution / next-action / error-recovery mixin (code-motion from service.py)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import base64
|
|
7
|
+
import http
|
|
8
|
+
import importlib
|
|
9
|
+
import json
|
|
10
|
+
import logging
|
|
11
|
+
import os
|
|
12
|
+
import re
|
|
13
|
+
import subprocess
|
|
14
|
+
import traceback
|
|
15
|
+
import time
|
|
16
|
+
from datetime import datetime
|
|
17
|
+
from io import BytesIO
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
from typing import Any, Callable, Dict, List, Optional, Type, TypeVar, Union, Tuple
|
|
20
|
+
from collections import deque # ADDED: Import deque for bounded collections
|
|
21
|
+
from agents.task.agent.tool_call_tracker import ToolCallTracker # Robust tool call ID tracking
|
|
22
|
+
|
|
23
|
+
from dotenv import load_dotenv
|
|
24
|
+
|
|
25
|
+
# Import centralized constants
|
|
26
|
+
from agents.task.constants import (
|
|
27
|
+
IMG_TOKENS,
|
|
28
|
+
LoopDetectionConfig,
|
|
29
|
+
DEFAULT_USER_ID,
|
|
30
|
+
MemoryConfig,
|
|
31
|
+
MAX_MCP_PER_STEP,
|
|
32
|
+
format_nag_exempt,
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
# Import POLYROB exceptions
|
|
36
|
+
from core.exceptions import (
|
|
37
|
+
AgentError,
|
|
38
|
+
ValidationError as ROBValidationError,
|
|
39
|
+
LLMResponseError,
|
|
40
|
+
ToolError
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
# Import billing exception for fail-fast handling
|
|
44
|
+
from core.exceptions import InsufficientCreditsError
|
|
45
|
+
|
|
46
|
+
# Import centralized utilities to avoid repeated inline imports
|
|
47
|
+
from agents.task.utils_json import normalize_action_schema
|
|
48
|
+
# Model limits now come from modules.llm.model_registry
|
|
49
|
+
|
|
50
|
+
# Native message types
|
|
51
|
+
from modules.llm.messages import (
|
|
52
|
+
AIMessage,
|
|
53
|
+
BaseMessage,
|
|
54
|
+
HumanMessage,
|
|
55
|
+
SystemMessage,
|
|
56
|
+
ToolMessage,
|
|
57
|
+
)
|
|
58
|
+
from modules.llm.adapters import BaseChatModel
|
|
59
|
+
from core.exceptions import (
|
|
60
|
+
RateLimitError,
|
|
61
|
+
LLMError,
|
|
62
|
+
LLMRateLimitError,
|
|
63
|
+
LLMAuthenticationError,
|
|
64
|
+
LLMConnectionError,
|
|
65
|
+
LLMContextLengthError,
|
|
66
|
+
LLMResponseError,
|
|
67
|
+
LLMPermanentError,
|
|
68
|
+
LLMProviderExhaustedError
|
|
69
|
+
)
|
|
70
|
+
# PIL Image imported locally in save_screenshot() method where needed
|
|
71
|
+
from pydantic import BaseModel, ConfigDict, ValidationError
|
|
72
|
+
|
|
73
|
+
from tools.browser.views import BrowserStateHistory, BrowserState
|
|
74
|
+
from agents.task.agent.message_manager.service import MessageManager
|
|
75
|
+
from agents.task.agent.prompts import SystemPrompt, AgentMessagePrompt
|
|
76
|
+
from agents.task.agent.views import (
|
|
77
|
+
ActionModel,
|
|
78
|
+
AgentBrain,
|
|
79
|
+
AgentError,
|
|
80
|
+
AgentHistory,
|
|
81
|
+
AgentHistoryList,
|
|
82
|
+
AgentOutput,
|
|
83
|
+
AgentStepInfo,
|
|
84
|
+
ActionResult,
|
|
85
|
+
)
|
|
86
|
+
from tools.browser.context import BrowserContext
|
|
87
|
+
from tools.dom.views import DOMElementNode, SelectorMap
|
|
88
|
+
from agents.task.telemetry.views import (
|
|
89
|
+
HumanApprovalRequestedEvent,
|
|
90
|
+
HumanApprovalDecisionEvent,
|
|
91
|
+
TodoStatusEvent,
|
|
92
|
+
AgentRunTelemetryEvent,
|
|
93
|
+
AgentEndTelemetryEvent,
|
|
94
|
+
ProviderFailureEvent,
|
|
95
|
+
ProviderFallbackSuccessEvent,
|
|
96
|
+
)
|
|
97
|
+
# ProductTelemetry no longer directly used - accessed via TelemetryManager
|
|
98
|
+
from agents.task.utils import time_execution_async, detect_llm_provider, extract_token_usage
|
|
99
|
+
# Safely import Google API exceptions
|
|
100
|
+
try:
|
|
101
|
+
from google.api_core.exceptions import ResourceExhausted
|
|
102
|
+
except ImportError:
|
|
103
|
+
# Create a dummy exception class if google-api-core is not installed
|
|
104
|
+
class ResourceExhausted(Exception):
|
|
105
|
+
pass
|
|
106
|
+
|
|
107
|
+
# Import from our own logging config
|
|
108
|
+
from agents.task.logging_config import get_task_logger
|
|
109
|
+
|
|
110
|
+
# Import centralized path management
|
|
111
|
+
from agents.task.path import pm
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
class NextActionInternalMixin:
|
|
118
|
+
"""Core LLM-invocation method (_get_next_action_internal) split whole out of
|
|
119
|
+
LLMRunnerMixin so llm_runner.py drops under 700L (P9). Agent composes it;
|
|
120
|
+
get_next_action calls it via MRO. Imports above are llm_runner's full set,
|
|
121
|
+
replicated so every name the method references resolves (post-MAX_MCP defense)."""
|
|
122
|
+
|
|
123
|
+
async def _stream_plain_fallback(self, current_messages, timeout_seconds) -> AIMessage:
|
|
124
|
+
"""Stream a plain (non-structured) LLM fallback call, accumulating content and
|
|
125
|
+
usage metadata into one AIMessage. Shared by both structured-output fallback
|
|
126
|
+
branches (H2: the two inline copies had drifted — one referenced an undefined
|
|
127
|
+
``usage_metadata`` and raised NameError every time that branch streamed)."""
|
|
128
|
+
full_content = ""
|
|
129
|
+
fallback_usage_metadata = None
|
|
130
|
+
|
|
131
|
+
async def _run():
|
|
132
|
+
nonlocal full_content, fallback_usage_metadata
|
|
133
|
+
async for chunk in self.llm.astream(current_messages):
|
|
134
|
+
if hasattr(chunk, 'content') and chunk.content:
|
|
135
|
+
full_content += chunk.content
|
|
136
|
+
await self.hitl_manager.stream_output(chunk.content)
|
|
137
|
+
if hasattr(chunk, 'usage_metadata') and chunk.usage_metadata:
|
|
138
|
+
fallback_usage_metadata = chunk.usage_metadata
|
|
139
|
+
|
|
140
|
+
await asyncio.wait_for(_run(), timeout=timeout_seconds)
|
|
141
|
+
return AIMessage(content=full_content, usage_metadata=fallback_usage_metadata)
|
|
142
|
+
|
|
143
|
+
async def _bill_llm_response(self, response, llm_duration, provider=None,
|
|
144
|
+
purpose="next_action"):
|
|
145
|
+
"""Bill exactly one finalized LLM response through the single billing path.
|
|
146
|
+
|
|
147
|
+
G1/G2 (telemetry audit 2026-07-04): billing used to be inline in the
|
|
148
|
+
native-tool branch only, so the structured-output and plain fallback
|
|
149
|
+
completions consumed tokens with NO billing record. This helper is called
|
|
150
|
+
from EVERY response-producing path. Idempotent per response object (marks
|
|
151
|
+
``_polyrob_billed``) so the same object is never charged twice; distinct
|
|
152
|
+
responses (a real 2nd API call) are each billed. Returns the token_usage dict.
|
|
153
|
+
"""
|
|
154
|
+
if response is None:
|
|
155
|
+
return None
|
|
156
|
+
if getattr(response, "_polyrob_billed", False):
|
|
157
|
+
return None
|
|
158
|
+
try:
|
|
159
|
+
setattr(response, "_polyrob_billed", True)
|
|
160
|
+
except Exception:
|
|
161
|
+
pass
|
|
162
|
+
|
|
163
|
+
provider = provider or getattr(self, 'llm_provider', 'unknown')
|
|
164
|
+
token_usage = extract_token_usage(response, provider)
|
|
165
|
+
input_tokens = token_usage.get('prompt_tokens', 0) or 0
|
|
166
|
+
output_tokens = token_usage.get('completion_tokens', 0) or 0
|
|
167
|
+
cached_tokens = token_usage.get('cached_tokens', 0) or 0
|
|
168
|
+
cache_creation_tokens = token_usage.get('cache_creation_tokens', 0) or 0
|
|
169
|
+
|
|
170
|
+
if self.usage_tracker and self.user_id:
|
|
171
|
+
try:
|
|
172
|
+
usage_record = await self.usage_tracker.record_llm_usage(
|
|
173
|
+
user_id=self.user_id,
|
|
174
|
+
session_id=self.session_id,
|
|
175
|
+
agent_id=self.agent_id,
|
|
176
|
+
model=self.model_name,
|
|
177
|
+
provider=provider,
|
|
178
|
+
input_tokens=input_tokens,
|
|
179
|
+
output_tokens=output_tokens,
|
|
180
|
+
cached_tokens=cached_tokens,
|
|
181
|
+
cache_creation_tokens=cache_creation_tokens,
|
|
182
|
+
duration_seconds=llm_duration,
|
|
183
|
+
component="agent",
|
|
184
|
+
purpose=purpose,
|
|
185
|
+
success=True
|
|
186
|
+
)
|
|
187
|
+
self.logger.info(
|
|
188
|
+
f"✓ Step {getattr(getattr(self, 'state', None), 'n_steps', '?')}: "
|
|
189
|
+
f"{input_tokens:,} in + {output_tokens:,} out = "
|
|
190
|
+
f"{input_tokens + output_tokens:,} tokens | "
|
|
191
|
+
f"API: ${usage_record.costs.api_cost_usd:.6f} → "
|
|
192
|
+
f"User: ${usage_record.costs.user_cost_usd:.6f} "
|
|
193
|
+
f"({usage_record.costs.credits_charged} credits)"
|
|
194
|
+
)
|
|
195
|
+
except InsufficientCreditsError:
|
|
196
|
+
self.logger.warning("⚠️ Session suspended due to insufficient credits")
|
|
197
|
+
raise
|
|
198
|
+
except Exception as e:
|
|
199
|
+
self.logger.error(f"Failed to record LLM usage: {e}", exc_info=True)
|
|
200
|
+
elif self.user_id:
|
|
201
|
+
# Fallback: telemetry only, NO billing (usage_tracker should always exist
|
|
202
|
+
# in production). G5: made visible so JSON/DB divergence is diagnosable.
|
|
203
|
+
self.logger.warning(
|
|
204
|
+
"usage_tracker not available - telemetry only, NO BILLING! "
|
|
205
|
+
"Check orchestrator initialization."
|
|
206
|
+
)
|
|
207
|
+
if getattr(self, 'telemetry_manager', None):
|
|
208
|
+
try:
|
|
209
|
+
self.telemetry_manager.capture_llm_usage(
|
|
210
|
+
component="agent",
|
|
211
|
+
purpose=purpose,
|
|
212
|
+
model_name=self.model_name,
|
|
213
|
+
duration_seconds=llm_duration,
|
|
214
|
+
success=True,
|
|
215
|
+
prompt_tokens=input_tokens,
|
|
216
|
+
completion_tokens=output_tokens,
|
|
217
|
+
cached_tokens=cached_tokens,
|
|
218
|
+
agent_id=self.agent_id
|
|
219
|
+
)
|
|
220
|
+
except Exception as e:
|
|
221
|
+
self.logger.debug(f"Failed to capture LLM telemetry: {e}")
|
|
222
|
+
return token_usage
|
|
223
|
+
|
|
224
|
+
async def _get_next_action_internal(self, input_messages: list[BaseMessage]) -> AgentOutput:
|
|
225
|
+
"""Internal implementation of get_next_action."""
|
|
226
|
+
from agents.task.robust_parse_config import RobustParseConfig
|
|
227
|
+
import asyncio
|
|
228
|
+
import time
|
|
229
|
+
|
|
230
|
+
# CRITICAL FIX: Clear tool call tracker at start of each get_next_action call
|
|
231
|
+
# This prevents accumulation of IDs across multiple calls within the same step
|
|
232
|
+
if self.tool_call_tracker and self.tool_call_tracker.has_active_calls():
|
|
233
|
+
active_calls = self.tool_call_tracker.get_current_step_calls()
|
|
234
|
+
if active_calls:
|
|
235
|
+
self.logger.debug(f"Clearing {len(active_calls)} stale tool calls from previous get_next_action call")
|
|
236
|
+
self.tool_call_tracker.complete_step()
|
|
237
|
+
|
|
238
|
+
# Clear any previous normalized tool calls (but use tracker for IDs)
|
|
239
|
+
if hasattr(self, '_current_normalized_tool_calls'):
|
|
240
|
+
delattr(self, '_current_normalized_tool_calls')
|
|
241
|
+
|
|
242
|
+
# Cut messages before LLM call only if we're really close to the limit
|
|
243
|
+
estimated_usage = self.message_manager.get_estimated_context_usage()
|
|
244
|
+
if estimated_usage > 0.92: # Warn at 92% context usage
|
|
245
|
+
self.logger.warning(f"High context usage: {estimated_usage:.1%} - consider checkpointing")
|
|
246
|
+
|
|
247
|
+
# Provider-aware format hint injection
|
|
248
|
+
# First determine if we'll be using native tools
|
|
249
|
+
provider = detect_llm_provider(None, self.model_name)
|
|
250
|
+
will_use_native_tools = (
|
|
251
|
+
self.use_native_tools and # User preference
|
|
252
|
+
self.controller and
|
|
253
|
+
# Use Controller's high-level API instead of directly accessing registry
|
|
254
|
+
self.controller.supports_native_tools(provider) # Provider capability
|
|
255
|
+
)
|
|
256
|
+
|
|
257
|
+
# Use ephemeral message API for format hints (P0 fix from upgrade_tasks.md)
|
|
258
|
+
format_hint_added = False
|
|
259
|
+
if RobustParseConfig.INJECT_FORMAT_HINT_EARLY and not will_use_native_tools:
|
|
260
|
+
# Only inject JSON format hint when NOT using native tools
|
|
261
|
+
formatting_message = HumanMessage(
|
|
262
|
+
content=f"""CRITICAL RESPONSE FORMAT:
|
|
263
|
+
Your response MUST be valid JSON with this exact structure:
|
|
264
|
+
{{
|
|
265
|
+
"current_state": {{
|
|
266
|
+
"page_summary": "Brief page summary",
|
|
267
|
+
"evaluation_previous_goal": "Success|Failed|Unknown",
|
|
268
|
+
"memory": "Key info to remember",
|
|
269
|
+
"next_goal": "What to do next",
|
|
270
|
+
"reasoning": "Why this action makes sense"
|
|
271
|
+
}},
|
|
272
|
+
"action": [{{"action_name": {{"param": "value"}}}}]
|
|
273
|
+
}}
|
|
274
|
+
|
|
275
|
+
CRITICAL: For "done" action use {{"done": {{"text": "message"}}}} - NOT "message" field!
|
|
276
|
+
Use double quotes only. Max {self.max_actions_per_step} actions."""
|
|
277
|
+
)
|
|
278
|
+
|
|
279
|
+
# Check if hint would fit within token limits using safety check
|
|
280
|
+
safety = self.message_manager.check_token_safety([formatting_message])
|
|
281
|
+
if safety['safe']:
|
|
282
|
+
# Use the new ephemeral message API instead of local append
|
|
283
|
+
self.message_manager.push_ephemeral_message(formatting_message)
|
|
284
|
+
format_hint_added = True
|
|
285
|
+
self.logger.debug("Pushed early format hint for JSON response mode")
|
|
286
|
+
else:
|
|
287
|
+
self.logger.warning(f"Format hint too large, would exceed safe token limit")
|
|
288
|
+
elif will_use_native_tools and RobustParseConfig.INJECT_FORMAT_HINT_EARLY \
|
|
289
|
+
and not format_nag_exempt(self.model_name, provider):
|
|
290
|
+
# For native tools, remind about JSON brain state format — but only for
|
|
291
|
+
# families that need it (T1-10): the prompt is authored for Claude and the
|
|
292
|
+
# family-note design deliberately gives it none, so the per-step nag was
|
|
293
|
+
# one wasted uncached message per step there.
|
|
294
|
+
native_tools_hint = HumanMessage(
|
|
295
|
+
content="""REMINDER: Your text content must be valid JSON with brain state fields:
|
|
296
|
+
{"memory": "...", "evaluation_previous_goal": "...", "next_goal": "...", "reasoning": "..."}
|
|
297
|
+
Then emit your function calls."""
|
|
298
|
+
)
|
|
299
|
+
# Use the new ephemeral message API
|
|
300
|
+
self.message_manager.push_ephemeral_message(native_tools_hint)
|
|
301
|
+
format_hint_added = True
|
|
302
|
+
self.logger.debug("Format hint prepared for injection")
|
|
303
|
+
|
|
304
|
+
# CRITICAL FIX: Don't consume ephemeral message yet - get regular messages first
|
|
305
|
+
# This prevents losing the format hint during token management
|
|
306
|
+
converted_input_messages = self.message_manager.get_messages() # NOT get_messages_for_llm() yet!
|
|
307
|
+
|
|
308
|
+
# Special handling for deepseek-reasoner after conversion
|
|
309
|
+
if self.model_name == 'deepseek-reasoner':
|
|
310
|
+
# DeepSeek needs additional message merging after conversion
|
|
311
|
+
converted_input_messages = self.message_manager.merge_successive_messages(converted_input_messages, HumanMessage)
|
|
312
|
+
converted_input_messages = self.message_manager.merge_successive_messages(converted_input_messages, AIMessage)
|
|
313
|
+
|
|
314
|
+
# Check token safety using MessageManager's API (SINGLE SOURCE OF TRUTH)
|
|
315
|
+
safety_check = self.message_manager.check_token_safety(raise_on_overflow=True)
|
|
316
|
+
self.logger.debug(
|
|
317
|
+
f"Token usage: {safety_check['usage_percent']:.1f}% "
|
|
318
|
+
f"({safety_check['current_tokens']}/{safety_check['max_limit']} tokens)"
|
|
319
|
+
)
|
|
320
|
+
|
|
321
|
+
# NOW get final messages with ephemeral message included (one-shot consumption)
|
|
322
|
+
converted_input_messages = self.message_manager.get_messages_for_llm()
|
|
323
|
+
|
|
324
|
+
# Prepare request info for session data
|
|
325
|
+
request_info = {
|
|
326
|
+
"model": self.model_name,
|
|
327
|
+
"model_library": self.chat_model_library,
|
|
328
|
+
"parameters": self._get_llm_parameters(),
|
|
329
|
+
"estimated_input_tokens": self.message_manager.get_token_count(),
|
|
330
|
+
"message_count": len(converted_input_messages),
|
|
331
|
+
"timestamp": __import__("time").time()
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
retry_count = 0
|
|
335
|
+
last_error = None
|
|
336
|
+
last_error_type = None # FIXED: Track error type for better retry logic
|
|
337
|
+
start_time = time.time()
|
|
338
|
+
|
|
339
|
+
while retry_count <= RobustParseConfig.MAX_PARSE_RETRIES:
|
|
340
|
+
try:
|
|
341
|
+
# Prepare messages for this attempt
|
|
342
|
+
current_messages = converted_input_messages.copy()
|
|
343
|
+
|
|
344
|
+
# FIXED: Only add retry hint on parse errors, not on first attempt
|
|
345
|
+
# Make retry hints provider-aware
|
|
346
|
+
if retry_count > 0 and last_error_type == "parse":
|
|
347
|
+
if will_use_native_tools:
|
|
348
|
+
# For native tools, emphasize correct tool call format
|
|
349
|
+
retry_hint = HumanMessage(content="Please ensure you emit valid function calls using the tool schemas provided.")
|
|
350
|
+
else:
|
|
351
|
+
# For JSON mode, use the standard JSON template hint
|
|
352
|
+
retry_hint = HumanMessage(content=RobustParseConfig.get_json_template_hint())
|
|
353
|
+
|
|
354
|
+
# Check if we have room for retry hint using MessageManager API
|
|
355
|
+
if self.message_manager.check_token_safety([retry_hint])['safe']:
|
|
356
|
+
current_messages.append(retry_hint)
|
|
357
|
+
self.logger.debug(f"Added retry hint on attempt {retry_count + 1}")
|
|
358
|
+
|
|
359
|
+
# Unified tool calling via registry
|
|
360
|
+
try:
|
|
361
|
+
# Track if we've already warned about structured output issues for this session
|
|
362
|
+
if not hasattr(self, '_structured_output_warned'):
|
|
363
|
+
self._structured_output_warned = False
|
|
364
|
+
|
|
365
|
+
# Determine provider from model name
|
|
366
|
+
provider = detect_llm_provider(None, self.model_name)
|
|
367
|
+
self.logger.info(f"[DEBUG_TOOLS] Detected provider: {provider}")
|
|
368
|
+
|
|
369
|
+
# Check if provider supports native tool calling
|
|
370
|
+
# Use Controller's high-level API instead of directly accessing registry
|
|
371
|
+
supports_native = self.controller and self.controller.supports_native_tools(provider)
|
|
372
|
+
self.logger.info(f"[DEBUG_TOOLS] Provider {provider} supports native tools: {supports_native}")
|
|
373
|
+
self.logger.info(f"[DEBUG_TOOLS] Has controller: {bool(self.controller)}")
|
|
374
|
+
|
|
375
|
+
if supports_native:
|
|
376
|
+
# Get ALL actions (core + tools) for this provider
|
|
377
|
+
# Use Controller's high-level API instead of directly accessing registry
|
|
378
|
+
tools = self.controller.get_all_actions_for_provider(provider)
|
|
379
|
+
self.logger.info(f"[DEBUG_TOOLS] Provider {provider} - Got {len(tools) if tools else 0} actions from registry")
|
|
380
|
+
self.logger.debug(f"Provider {provider} - Got {len(tools) if tools else 0} actions from registry")
|
|
381
|
+
|
|
382
|
+
# Debug: Log the actual schemas being generated (only on first step)
|
|
383
|
+
if tools and self.state.n_steps == 1:
|
|
384
|
+
import json
|
|
385
|
+
self.logger.debug(f"Generated {len(tools)} tool schemas for {provider}:")
|
|
386
|
+
# Ensure tools is a list for safe slicing
|
|
387
|
+
tools_list = list(tools) if not isinstance(tools, list) else tools
|
|
388
|
+
for i, tool in enumerate(tools_list[:3]): # Log first 3
|
|
389
|
+
tool_str = json.dumps(tool, indent=2) if isinstance(tool, dict) else str(tool)
|
|
390
|
+
self.logger.debug(f" Tool schema {i}: {tool_str[:300]}...")
|
|
391
|
+
|
|
392
|
+
# NO LIMITS: Pass all tools to the LLM - modern models can handle it
|
|
393
|
+
# Note: "tools" = LLM function calling schemas, "actions" = our internal Registry actions
|
|
394
|
+
self.logger.info(f"Using all {len(tools) if tools else 0} tools for native function calling")
|
|
395
|
+
|
|
396
|
+
if tools and len(tools) > 0:
|
|
397
|
+
# Ensure tools is a list for safe slicing
|
|
398
|
+
tools_list = list(tools) if not isinstance(tools, list) else tools
|
|
399
|
+
action_names = [t.get('function', {}).get('name') if isinstance(t, dict) else getattr(t, 'name', 'unknown') for t in tools_list[:5]]
|
|
400
|
+
if len(tools_list) > 5:
|
|
401
|
+
action_names.append(f"... +{len(tools_list)-5} more")
|
|
402
|
+
self.logger.debug(f"Sample tool names: {action_names}")
|
|
403
|
+
|
|
404
|
+
# Try native tool calling first
|
|
405
|
+
self.logger.debug(f"Using native tool calling for {provider} with {len(tools)} actions")
|
|
406
|
+
self.logger.info(f"[DEBUG_TOOLS] About to call LLM with tools parameter")
|
|
407
|
+
self.logger.info(f"[DEBUG_TOOLS] Tools type: {type(tools)}, Tools count: {len(tools) if tools else 0}")
|
|
408
|
+
self.logger.info(f"[DEBUG_TOOLS] LLM adapter type: {type(self.llm).__name__}")
|
|
409
|
+
try:
|
|
410
|
+
# Calculate timeout using MessageManager
|
|
411
|
+
tool_count = len(self.controller.get_action_names()) if self.controller else 0
|
|
412
|
+
timeout_seconds = self.message_manager.calculate_llm_timeout(
|
|
413
|
+
tool_count=tool_count,
|
|
414
|
+
use_vision=self.use_vision
|
|
415
|
+
)
|
|
416
|
+
|
|
417
|
+
# Call with tools with better error handling
|
|
418
|
+
try:
|
|
419
|
+
parsed = None # Initialize to prevent NameError
|
|
420
|
+
llm_start = time.time()
|
|
421
|
+
|
|
422
|
+
# Track LLM call state for stall detection
|
|
423
|
+
self._llm_call_in_progress = True
|
|
424
|
+
self._llm_call_start_time = llm_start
|
|
425
|
+
|
|
426
|
+
# CONSISTENT ADAPTER PATTERN:
|
|
427
|
+
# Our adapters (OpenAIAdapter, DeepSeekAdapter, etc.) accept tools via kwargs
|
|
428
|
+
# They extract tools from kwargs and call client.generate_agent_response()
|
|
429
|
+
# This provides consistent interface across all providers
|
|
430
|
+
# Stream if supported and callbacks registered
|
|
431
|
+
chunk_count = 0 # Track streaming chunks for telemetry
|
|
432
|
+
if self._supports_streaming() and self.hitl_manager.has_streaming_callbacks():
|
|
433
|
+
self.logger.debug("Using streaming mode for LLM call")
|
|
434
|
+
self.logger.info(f"[DEBUG_TOOLS] Calling llm.astream with tools={len(tools) if tools else 0}")
|
|
435
|
+
full_content = ""
|
|
436
|
+
collected_tool_calls = []
|
|
437
|
+
|
|
438
|
+
usage_metadata = None # Collect usage metadata from final chunk
|
|
439
|
+
async def stream_with_timeout():
|
|
440
|
+
nonlocal full_content, collected_tool_calls, chunk_count, usage_metadata
|
|
441
|
+
async for chunk in self.llm.astream(current_messages, tools=tools):
|
|
442
|
+
# Extract content
|
|
443
|
+
if hasattr(chunk, 'content') and chunk.content:
|
|
444
|
+
# Handle both string and list content in streaming
|
|
445
|
+
chunk_text = chunk.content if isinstance(chunk.content, str) else "".join(str(b.text if hasattr(b, "text") else b) for b in chunk.content if b)
|
|
446
|
+
full_content += chunk_text
|
|
447
|
+
await self.hitl_manager.stream_output(chunk_text)
|
|
448
|
+
chunk_count += 1
|
|
449
|
+
|
|
450
|
+
# Collect tool calls
|
|
451
|
+
if hasattr(chunk, 'tool_calls') and chunk.tool_calls:
|
|
452
|
+
collected_tool_calls.extend(chunk.tool_calls)
|
|
453
|
+
|
|
454
|
+
# Collect usage metadata (usually in final chunk)
|
|
455
|
+
if hasattr(chunk, 'usage_metadata') and chunk.usage_metadata:
|
|
456
|
+
usage_metadata = chunk.usage_metadata
|
|
457
|
+
|
|
458
|
+
|
|
459
|
+
await asyncio.wait_for(stream_with_timeout(), timeout=timeout_seconds)
|
|
460
|
+
|
|
461
|
+
# Build complete response
|
|
462
|
+
response = AIMessage(content=full_content, usage_metadata=usage_metadata)
|
|
463
|
+
if collected_tool_calls:
|
|
464
|
+
response.tool_calls = collected_tool_calls
|
|
465
|
+
else:
|
|
466
|
+
# Regular batch call
|
|
467
|
+
self.logger.info(f"[DEBUG_TOOLS] Calling llm.ainvoke with tools={len(tools) if tools else 0}")
|
|
468
|
+
response = await asyncio.wait_for(
|
|
469
|
+
self.llm.ainvoke(current_messages, tools=tools),
|
|
470
|
+
timeout=timeout_seconds
|
|
471
|
+
)
|
|
472
|
+
self.logger.info(f"[DEBUG_TOOLS] llm.ainvoke returned, response type: {type(response).__name__}")
|
|
473
|
+
llm_duration = time.time() - llm_start
|
|
474
|
+
|
|
475
|
+
# Clear LLM call tracking
|
|
476
|
+
self._llm_call_in_progress = False
|
|
477
|
+
self._llm_call_start_time = None
|
|
478
|
+
|
|
479
|
+
# Extract token usage from response using centralized utility
|
|
480
|
+
token_usage = extract_token_usage(response, provider)
|
|
481
|
+
input_tokens = token_usage.get('prompt_tokens', 0) or 0
|
|
482
|
+
output_tokens = token_usage.get('completion_tokens', 0) or 0
|
|
483
|
+
cached_tokens = token_usage.get('cached_tokens', 0) or 0
|
|
484
|
+
cache_creation_tokens = token_usage.get('cache_creation_tokens', 0) or 0
|
|
485
|
+
|
|
486
|
+
self.logger.debug(
|
|
487
|
+
f"Extracted tokens: {input_tokens} input + {output_tokens} output "
|
|
488
|
+
f"(cached: {cached_tokens})"
|
|
489
|
+
)
|
|
490
|
+
|
|
491
|
+
# Record LLM usage to ALL systems atomically (SINGLE WRITE PATH)
|
|
492
|
+
# This replaces separate calls to usage_meter + telemetry_manager
|
|
493
|
+
if self.usage_tracker and self.user_id:
|
|
494
|
+
try:
|
|
495
|
+
usage_record = await self.usage_tracker.record_llm_usage(
|
|
496
|
+
user_id=self.user_id,
|
|
497
|
+
session_id=self.session_id,
|
|
498
|
+
agent_id=self.agent_id,
|
|
499
|
+
model=self.model_name,
|
|
500
|
+
provider=getattr(self, 'llm_provider', 'unknown'),
|
|
501
|
+
input_tokens=input_tokens,
|
|
502
|
+
output_tokens=output_tokens,
|
|
503
|
+
cached_tokens=cached_tokens,
|
|
504
|
+
cache_creation_tokens=cache_creation_tokens,
|
|
505
|
+
duration_seconds=llm_duration,
|
|
506
|
+
component="agent",
|
|
507
|
+
purpose="next_action",
|
|
508
|
+
success=True
|
|
509
|
+
)
|
|
510
|
+
|
|
511
|
+
# Log what user was charged (transparent billing)
|
|
512
|
+
self.logger.info(
|
|
513
|
+
f"✓ Step {self.state.n_steps}: {input_tokens:,} in + {output_tokens:,} out = "
|
|
514
|
+
f"{input_tokens + output_tokens:,} tokens | "
|
|
515
|
+
f"API: ${usage_record.costs.api_cost_usd:.6f} → "
|
|
516
|
+
f"User: ${usage_record.costs.user_cost_usd:.6f} "
|
|
517
|
+
f"({usage_record.costs.credits_charged} credits)"
|
|
518
|
+
)
|
|
519
|
+
|
|
520
|
+
except InsufficientCreditsError:
|
|
521
|
+
# Billing error - stop execution immediately
|
|
522
|
+
self.logger.warning(
|
|
523
|
+
f"⚠️ Session suspended due to insufficient credits"
|
|
524
|
+
)
|
|
525
|
+
# Re-raise to propagate up to orchestrator
|
|
526
|
+
raise
|
|
527
|
+
except Exception as e:
|
|
528
|
+
self.logger.error(f"Failed to record LLM usage: {e}", exc_info=True)
|
|
529
|
+
# Continue execution - don't fail agent for tracking errors
|
|
530
|
+
elif self.user_id:
|
|
531
|
+
# Fallback: just log telemetry without billing
|
|
532
|
+
# In production, usage_tracker should always be available
|
|
533
|
+
self.logger.warning(
|
|
534
|
+
"usage_tracker not available - telemetry only, NO BILLING! "
|
|
535
|
+
"Check orchestrator initialization."
|
|
536
|
+
)
|
|
537
|
+
|
|
538
|
+
# Capture to telemetry for display (no billing)
|
|
539
|
+
if self.telemetry_manager:
|
|
540
|
+
try:
|
|
541
|
+
self.telemetry_manager.capture_llm_usage(
|
|
542
|
+
component="agent",
|
|
543
|
+
purpose="next_action",
|
|
544
|
+
model_name=self.model_name,
|
|
545
|
+
duration_seconds=llm_duration,
|
|
546
|
+
success=True,
|
|
547
|
+
prompt_tokens=input_tokens,
|
|
548
|
+
completion_tokens=output_tokens,
|
|
549
|
+
cached_tokens=cached_tokens,
|
|
550
|
+
agent_id=self.agent_id
|
|
551
|
+
)
|
|
552
|
+
except Exception as e:
|
|
553
|
+
self.logger.debug(f"Failed to capture LLM telemetry: {e}")
|
|
554
|
+
|
|
555
|
+
# Emit streaming telemetry if streaming was used
|
|
556
|
+
if self._supports_streaming() and self.hitl_manager.has_streaming_callbacks() and chunk_count > 0:
|
|
557
|
+
if self.telemetry_manager:
|
|
558
|
+
try:
|
|
559
|
+
from agents.task.telemetry.views import StreamingOutputEvent
|
|
560
|
+
|
|
561
|
+
event = StreamingOutputEvent(
|
|
562
|
+
agent_id=self.agent_id,
|
|
563
|
+
step=self.state.n_steps,
|
|
564
|
+
total_chunks=chunk_count,
|
|
565
|
+
total_chars=len(full_content) if full_content else 0,
|
|
566
|
+
provider=getattr(self, 'llm_provider', 'unknown'),
|
|
567
|
+
duration_seconds=llm_duration,
|
|
568
|
+
callbacks_count=self.hitl_manager.get_callback_count(),
|
|
569
|
+
callback_failures=self.hitl_manager._callback_failures
|
|
570
|
+
)
|
|
571
|
+
self.telemetry_manager.capture_event(event)
|
|
572
|
+
except Exception as e:
|
|
573
|
+
self.logger.debug(f"Failed to emit streaming telemetry: {e}")
|
|
574
|
+
|
|
575
|
+
# Debug: Log detailed response information
|
|
576
|
+
if hasattr(response, 'tool_calls'):
|
|
577
|
+
self.logger.debug(f"Tool calls in response: {len(response.tool_calls) if response.tool_calls else 0}")
|
|
578
|
+
if response.tool_calls:
|
|
579
|
+
for tc in response.tool_calls[:3]: # Log first 3
|
|
580
|
+
self.logger.debug(f" Tool call: {tc.function.name if hasattr(tc, 'function') else tc}")
|
|
581
|
+
if hasattr(response, 'content'):
|
|
582
|
+
# Handle both string and list content formats
|
|
583
|
+
content_for_preview = response.content if response.content else "None"
|
|
584
|
+
if isinstance(content_for_preview, list):
|
|
585
|
+
content_preview = str(content_for_preview)[:200]
|
|
586
|
+
else:
|
|
587
|
+
content_preview = str(content_for_preview)[:200]
|
|
588
|
+
self.logger.debug(f"Response content preview: {content_preview}...")
|
|
589
|
+
|
|
590
|
+
# Store the raw response for later token extraction
|
|
591
|
+
raw_tool_response = response
|
|
592
|
+
|
|
593
|
+
# Initialize actions to empty list (will be populated if tool calls exist)
|
|
594
|
+
actions = []
|
|
595
|
+
normalized_tool_calls = []
|
|
596
|
+
|
|
597
|
+
# Check if response contains tool calls
|
|
598
|
+
if hasattr(response, 'tool_calls') and response.tool_calls:
|
|
599
|
+
self.logger.info(f"[NATIVE_TOOLS] Received {len(response.tool_calls)} tool_calls from LLM")
|
|
600
|
+
|
|
601
|
+
# Get provider name for normalization
|
|
602
|
+
provider = getattr(self, 'llm_provider', None) or 'unknown'
|
|
603
|
+
|
|
604
|
+
# Process tool calls using ToolCallBuilder + Registry pipeline
|
|
605
|
+
try:
|
|
606
|
+
from agents.task.agent.message_manager.tool_call_builder import ToolCallBuilder
|
|
607
|
+
|
|
608
|
+
# STEP 1: Normalize tool calls using ToolCallBuilder
|
|
609
|
+
normalized_tool_calls = [
|
|
610
|
+
ToolCallBuilder.normalize_and_correct(tc, provider=provider)
|
|
611
|
+
for tc in response.tool_calls
|
|
612
|
+
]
|
|
613
|
+
self.logger.info(f"Normalized {len(response.tool_calls)} tool_calls via ToolCallBuilder")
|
|
614
|
+
|
|
615
|
+
# STEP 2: Register with tracker FIRST (before MessageManager)
|
|
616
|
+
if self.tool_call_tracker and normalized_tool_calls:
|
|
617
|
+
registered_ids = self.tool_call_tracker.register_tool_calls(normalized_tool_calls)
|
|
618
|
+
self.logger.info(f"[NATIVE_TOOLS] ✅ Registered {len(registered_ids)} tool calls with tracker")
|
|
619
|
+
|
|
620
|
+
# ✅ FIX #6: Don't add model output here - let step() handle it
|
|
621
|
+
# This eliminates duplicate add_model_output() calls
|
|
622
|
+
|
|
623
|
+
# STEP 3: Convert to actions using Controller's high-level API
|
|
624
|
+
actions = self.controller.tool_calls_to_actions(normalized_tool_calls)
|
|
625
|
+
self.logger.info(f"Converted {len(normalized_tool_calls)} tool_calls -> {len(actions)} actions via Controller")
|
|
626
|
+
|
|
627
|
+
# Extract tool call IDs for debugging
|
|
628
|
+
tool_call_ids = [tc.get('id') for tc in normalized_tool_calls if tc.get('id')]
|
|
629
|
+
|
|
630
|
+
# Store normalized tool calls for MessageManager (but NOT IDs - use tracker)
|
|
631
|
+
self._current_normalized_tool_calls = normalized_tool_calls # Store for MessageManager
|
|
632
|
+
|
|
633
|
+
# Log for debugging
|
|
634
|
+
self.logger.debug(f"Stored {len(tool_call_ids)} tool call IDs: {tool_call_ids}")
|
|
635
|
+
self.logger.debug(f"Stored {len(normalized_tool_calls)} normalized tool calls")
|
|
636
|
+
|
|
637
|
+
# Check if we got zero actions despite having tool calls
|
|
638
|
+
if len(actions) == 0 and len(normalized_tool_calls) > 0:
|
|
639
|
+
self.logger.error(f"❌ Failed to convert {len(normalized_tool_calls)} tool_calls to actions")
|
|
640
|
+
|
|
641
|
+
# Log what failed
|
|
642
|
+
for i, tc in enumerate(normalized_tool_calls):
|
|
643
|
+
tc_name = tc.get('name', 'unknown')
|
|
644
|
+
tc_args = tc.get('args', {})
|
|
645
|
+
self.logger.error(f" Tool call {i}: name='{tc_name}', args={tc_args}")
|
|
646
|
+
|
|
647
|
+
# Log available actions for comparison
|
|
648
|
+
# Use Controller's high-level API instead of directly accessing registry
|
|
649
|
+
available = self.controller.list_actions()[:20]
|
|
650
|
+
self.logger.error(f" Available actions (first 20): {available}")
|
|
651
|
+
|
|
652
|
+
# This is a CRITICAL error - raise exception instead of continuing
|
|
653
|
+
raise ValueError(
|
|
654
|
+
f"Tool call conversion failed: LLM called {[tc.get('name') for tc in normalized_tool_calls]} "
|
|
655
|
+
f"but these actions don't exist in registry. Check tool loading and action registration."
|
|
656
|
+
)
|
|
657
|
+
|
|
658
|
+
except Exception as conversion_error:
|
|
659
|
+
self.logger.error(f"Error processing tool_calls: {conversion_error}", exc_info=True)
|
|
660
|
+
# Fall back to safe default
|
|
661
|
+
actions = []
|
|
662
|
+
normalized_tool_calls = []
|
|
663
|
+
# Let execution continue with empty actions - will trigger appropriate error handling
|
|
664
|
+
|
|
665
|
+
# Initialize action_list to prevent undefined variable errors
|
|
666
|
+
action_list = []
|
|
667
|
+
action_tool_call_ids = [] # P0-2: parallel to action_list; re-stamped onto parsed.action
|
|
668
|
+
|
|
669
|
+
if actions:
|
|
670
|
+
# COMPLEX SITUATION: We need BOTH behaviors!
|
|
671
|
+
# 1. Validator needs ActionModel instances (to call .model_dump())
|
|
672
|
+
# 2. AgentOutput creation needs dicts (Pydantic type validation)
|
|
673
|
+
#
|
|
674
|
+
# SOLUTION: Keep instances in actions list, convert to dicts for AgentOutput
|
|
675
|
+
# The validator will use model_output.action (which has instances)
|
|
676
|
+
#
|
|
677
|
+
# But wait - we're creating AgentOutput here with action_list
|
|
678
|
+
# And validator validates model_output.action
|
|
679
|
+
# These are the SAME thing!
|
|
680
|
+
#
|
|
681
|
+
# The issue: AgentOutput type annotation is list[ActionModel] (base class)
|
|
682
|
+
# But we're passing list[ActionModel_toolname] (subclasses)
|
|
683
|
+
# Pydantic rejects subclasses in strict mode!
|
|
684
|
+
#
|
|
685
|
+
# REAL FIX: Convert to dicts for AgentOutput, validator will handle them
|
|
686
|
+
#
|
|
687
|
+
# P0-2: model_dump(exclude_unset=True) DROPS the `_tool_call_id`
|
|
688
|
+
# PrivateAttr that tool_calls_to_actions stamped onto each instance
|
|
689
|
+
# (PrivateAttrs are not serialized). AgentOutput then re-validates the
|
|
690
|
+
# dicts into FRESH instances with _tool_call_id=None — so downstream
|
|
691
|
+
# execution.py always read None, `_pair_results_to_calls.have_ids` was
|
|
692
|
+
# ALWAYS False, and result↔call pairing silently fell to POSITION every
|
|
693
|
+
# step (misattributing results whenever the executor skips a failed-
|
|
694
|
+
# validation action, MCP throttling reorders, or is_done breaks mid-list).
|
|
695
|
+
# Capture the ids here and re-stamp them onto parsed.action below.
|
|
696
|
+
action_tool_call_ids = []
|
|
697
|
+
for action in actions:
|
|
698
|
+
action_tool_call_ids.append(getattr(action, '_tool_call_id', None))
|
|
699
|
+
if hasattr(action, 'model_dump'):
|
|
700
|
+
# Convert to dict - validator accepts both dicts and instances
|
|
701
|
+
action_list.append(action.model_dump(exclude_unset=True))
|
|
702
|
+
else:
|
|
703
|
+
action_list.append(action)
|
|
704
|
+
|
|
705
|
+
# Extract brain state from response content using JSON parser
|
|
706
|
+
from agents.task.utils_json import extract_brain_state_from_json
|
|
707
|
+
|
|
708
|
+
brain_state = None
|
|
709
|
+
# Normalize content to string (handles both string and list formats)
|
|
710
|
+
# Some providers (Gemini) return content as list of blocks
|
|
711
|
+
content_str = None
|
|
712
|
+
if response.content:
|
|
713
|
+
if isinstance(response.content, str):
|
|
714
|
+
content_str = response.content
|
|
715
|
+
elif isinstance(response.content, list):
|
|
716
|
+
# Extract text from content blocks
|
|
717
|
+
content_str = ""
|
|
718
|
+
for block in response.content:
|
|
719
|
+
if isinstance(block, str):
|
|
720
|
+
content_str += block
|
|
721
|
+
elif hasattr(block, 'text'):
|
|
722
|
+
content_str += block.text
|
|
723
|
+
elif isinstance(block, dict) and 'text' in block:
|
|
724
|
+
content_str += block['text']
|
|
725
|
+
else:
|
|
726
|
+
content_str = str(response.content)
|
|
727
|
+
|
|
728
|
+
content_available = content_str and content_str.strip()
|
|
729
|
+
|
|
730
|
+
if content_available:
|
|
731
|
+
try:
|
|
732
|
+
brain_fields = extract_brain_state_from_json(content_str)
|
|
733
|
+
brain_state = AgentBrain(**brain_fields)
|
|
734
|
+
self.logger.info(f"✅ Extracted brain state: {brain_state.memory[:100]}")
|
|
735
|
+
|
|
736
|
+
# ✅ CRITICAL FIX (Nov 17, 2025): Validate memory is NOT identical to previous step
|
|
737
|
+
# This prevents the memory rejection loop where LLM repeats same text
|
|
738
|
+
if hasattr(self, '_last_brain_state') and self._last_brain_state:
|
|
739
|
+
previous_memory = self._last_brain_state.memory if hasattr(self._last_brain_state, 'memory') else ""
|
|
740
|
+
current_memory = brain_state.memory
|
|
741
|
+
|
|
742
|
+
# Check if memory is identical (exact match)
|
|
743
|
+
if previous_memory and current_memory and previous_memory.strip() == current_memory.strip():
|
|
744
|
+
self.logger.warning(
|
|
745
|
+
f"⚠️ MEMORY VALIDATION FAILED: Memory identical to previous step!\n"
|
|
746
|
+
f" Previous: {previous_memory[:150]}...\n"
|
|
747
|
+
f" Current: {current_memory[:150]}...\n"
|
|
748
|
+
f" This violates CRITICAL MEMORY RULE #3: Memory MUST be unique each step.\n"
|
|
749
|
+
f" Will attempt to auto-fix by synthesizing step-specific memory from actions."
|
|
750
|
+
)
|
|
751
|
+
# Mark for synthesis - will be regenerated after actions execute
|
|
752
|
+
brain_state = None
|
|
753
|
+
|
|
754
|
+
# Check if memory is suspiciously similar (>90% overlap by simple word count)
|
|
755
|
+
elif previous_memory and current_memory:
|
|
756
|
+
prev_words = set(previous_memory.lower().split())
|
|
757
|
+
curr_words = set(current_memory.lower().split())
|
|
758
|
+
if prev_words and curr_words:
|
|
759
|
+
overlap = len(prev_words & curr_words) / max(len(prev_words), len(curr_words))
|
|
760
|
+
if overlap > 0.90:
|
|
761
|
+
self.logger.warning(
|
|
762
|
+
f"⚠️ MEMORY VALIDATION WARNING: Memory {overlap:.0%} similar to previous step.\n"
|
|
763
|
+
f" LLM may be repeating instead of adding new step-specific information."
|
|
764
|
+
)
|
|
765
|
+
|
|
766
|
+
# Store current brain state for next validation
|
|
767
|
+
self._last_brain_state = brain_state if brain_state else self._last_brain_state
|
|
768
|
+
|
|
769
|
+
except Exception as e:
|
|
770
|
+
# ✅ FIX: Defer synthesis until after actions execute
|
|
771
|
+
# This allows synthesis to use actual action results
|
|
772
|
+
self.logger.info(f"Brain state extraction failed: {e}. Will synthesize after actions execute.")
|
|
773
|
+
brain_state = None # Synthesis #1 will handle this after actions
|
|
774
|
+
else:
|
|
775
|
+
# ✅ FIX: LLM returned tool calls WITHOUT text content
|
|
776
|
+
# Defer synthesis until after actions execute to use actual results
|
|
777
|
+
self.logger.info(
|
|
778
|
+
f"LLM returned tool calls without content (common with OpenAI). "
|
|
779
|
+
f"Will synthesize brain state after actions execute."
|
|
780
|
+
)
|
|
781
|
+
brain_state = None # Synthesis #1 will handle this after actions
|
|
782
|
+
|
|
783
|
+
# Create parsed output with extracted brain state and converted actions
|
|
784
|
+
# This happens for BOTH cases: with actions or without actions
|
|
785
|
+
# If brain_state is None, use a placeholder that will be replaced by synthesis
|
|
786
|
+
if brain_state is None:
|
|
787
|
+
brain_state = AgentBrain(
|
|
788
|
+
page_summary="",
|
|
789
|
+
memory="Synthesis pending - will be generated after actions execute",
|
|
790
|
+
evaluation_previous_goal="Pending",
|
|
791
|
+
next_goal="Pending",
|
|
792
|
+
reasoning="Synthesis pending"
|
|
793
|
+
)
|
|
794
|
+
self.logger.info("Using placeholder brain state - will synthesize after actions")
|
|
795
|
+
|
|
796
|
+
parsed = self.AgentOutput(
|
|
797
|
+
current_state=brain_state,
|
|
798
|
+
action=action_list
|
|
799
|
+
)
|
|
800
|
+
|
|
801
|
+
# P0-2: re-stamp the tool_call_id PrivateAttr that AgentOutput's
|
|
802
|
+
# re-validation dropped, so identity pairing (result_processing.
|
|
803
|
+
# _pair_results_to_calls) works instead of falling to position.
|
|
804
|
+
# parsed.action is built 1:1 in-order from action_list, so zip aligns.
|
|
805
|
+
try:
|
|
806
|
+
for _act, _tcid in zip(parsed.action, action_tool_call_ids):
|
|
807
|
+
if _tcid is not None:
|
|
808
|
+
_act._tool_call_id = _tcid
|
|
809
|
+
except Exception as _restamp_err:
|
|
810
|
+
self.logger.debug(f"tool_call_id re-stamp skipped: {_restamp_err}")
|
|
811
|
+
|
|
812
|
+
except asyncio.TimeoutError:
|
|
813
|
+
self.logger.error(f"LLM call timed out after {timeout_seconds} seconds with {len(tools)} tools", exc_info=True)
|
|
814
|
+
raise
|
|
815
|
+
except TypeError as type_error:
|
|
816
|
+
# Handle cases where bind_tools() is not supported or has invalid tool schemas
|
|
817
|
+
self.logger.error(f"Failed to bind tools to LLM: {type_error}", exc_info=True)
|
|
818
|
+
self.logger.warning("Falling back to non-tool calling mode")
|
|
819
|
+
# Set parsed to None to trigger fallback to structured output
|
|
820
|
+
parsed = None
|
|
821
|
+
# Don't raise - let it fall through to structured output fallback
|
|
822
|
+
except Exception as llm_error:
|
|
823
|
+
self.logger.error(f"LLM call failed with {len(tools)} tools: {llm_error}", exc_info=True)
|
|
824
|
+
# Log tool sample for debugging
|
|
825
|
+
if tools:
|
|
826
|
+
sample = tools[:2] if len(tools) > 2 else tools
|
|
827
|
+
self.logger.debug(f"Sample tools that caused error: {sample}")
|
|
828
|
+
raise
|
|
829
|
+
|
|
830
|
+
except Exception as tool_error:
|
|
831
|
+
if not self._structured_output_warned:
|
|
832
|
+
self.logger.warning(f"Native tool calling failed for {provider}: {tool_error}")
|
|
833
|
+
self._structured_output_warned = True
|
|
834
|
+
parsed = None
|
|
835
|
+
else:
|
|
836
|
+
# No tools available - fall back to structured output
|
|
837
|
+
parsed = None
|
|
838
|
+
else:
|
|
839
|
+
# Provider doesn't support native tools - use structured output
|
|
840
|
+
parsed = None
|
|
841
|
+
|
|
842
|
+
# Fall back to structured output if native tools didn't work
|
|
843
|
+
if parsed is None:
|
|
844
|
+
self.logger.info("Native tool calling didn't produce parsed output - falling back to structured output")
|
|
845
|
+
try:
|
|
846
|
+
# Try structured output based on provider capabilities
|
|
847
|
+
if provider == 'openai' or 'gpt' in self.model_name.lower():
|
|
848
|
+
# OpenAI - use function_calling method
|
|
849
|
+
structured_llm = self.llm.with_structured_output(
|
|
850
|
+
self.AgentOutput,
|
|
851
|
+
method="function_calling",
|
|
852
|
+
include_raw=True
|
|
853
|
+
)
|
|
854
|
+
else:
|
|
855
|
+
# Other providers - use default structured output
|
|
856
|
+
structured_llm = self.llm.with_structured_output(
|
|
857
|
+
self.AgentOutput,
|
|
858
|
+
include_raw=True
|
|
859
|
+
)
|
|
860
|
+
|
|
861
|
+
# Make the call
|
|
862
|
+
tool_count = len(self.controller.get_action_names()) if self.controller else 0
|
|
863
|
+
timeout_seconds = self.message_manager.calculate_llm_timeout(
|
|
864
|
+
tool_count=tool_count,
|
|
865
|
+
use_vision=self.use_vision
|
|
866
|
+
)
|
|
867
|
+
_fb_start = time.time()
|
|
868
|
+
response = await asyncio.wait_for(
|
|
869
|
+
structured_llm.ainvoke(current_messages),
|
|
870
|
+
timeout=timeout_seconds
|
|
871
|
+
)
|
|
872
|
+
# G2: structured-output fallback completion must be billed too.
|
|
873
|
+
await self._bill_llm_response(response, time.time() - _fb_start, provider, purpose="next_action_structured")
|
|
874
|
+
|
|
875
|
+
# Extract parsed result
|
|
876
|
+
if isinstance(response, dict) and 'parsed' in response:
|
|
877
|
+
parsed = response['parsed']
|
|
878
|
+
self.logger.info("Got parsed output from structured response")
|
|
879
|
+
elif isinstance(response, self.AgentOutput):
|
|
880
|
+
parsed = response
|
|
881
|
+
self.logger.info("Got direct AgentOutput from structured response")
|
|
882
|
+
else:
|
|
883
|
+
parsed = None
|
|
884
|
+
self.logger.warning("Structured output didn't return valid parsed output")
|
|
885
|
+
|
|
886
|
+
except Exception as struct_error:
|
|
887
|
+
if not self._structured_output_warned:
|
|
888
|
+
self.logger.warning(f"Structured output failed: {struct_error}")
|
|
889
|
+
self._structured_output_warned = True
|
|
890
|
+
self.logger.info("Falling back to regular LLM call")
|
|
891
|
+
# Fall back to regular call
|
|
892
|
+
try:
|
|
893
|
+
tool_count = len(self.controller.get_action_names()) if self.controller else 0
|
|
894
|
+
timeout_seconds = self.message_manager.calculate_llm_timeout(
|
|
895
|
+
tool_count=tool_count,
|
|
896
|
+
use_vision=self.use_vision
|
|
897
|
+
)
|
|
898
|
+
# Stream if supported and callbacks registered
|
|
899
|
+
_fb_start = time.time()
|
|
900
|
+
if self._supports_streaming() and self.hitl_manager.has_streaming_callbacks():
|
|
901
|
+
self.logger.debug("Using streaming mode for fallback LLM call")
|
|
902
|
+
response = await self._stream_plain_fallback(current_messages, timeout_seconds)
|
|
903
|
+
else:
|
|
904
|
+
response = await asyncio.wait_for(
|
|
905
|
+
self.llm.ainvoke(current_messages),
|
|
906
|
+
timeout=timeout_seconds
|
|
907
|
+
)
|
|
908
|
+
# G2: plain fallback completion must be billed too.
|
|
909
|
+
await self._bill_llm_response(response, time.time() - _fb_start, provider, purpose="next_action_fallback")
|
|
910
|
+
except asyncio.TimeoutError:
|
|
911
|
+
self.logger.error(f"LLM call timed out after {timeout_seconds:.0f} seconds", exc_info=True)
|
|
912
|
+
raise
|
|
913
|
+
parsed = None
|
|
914
|
+
|
|
915
|
+
except Exception as structured_error:
|
|
916
|
+
if not self._structured_output_warned:
|
|
917
|
+
self.logger.warning(f"All structured output attempts failed: {structured_error}, using manual parsing")
|
|
918
|
+
self._structured_output_warned = True
|
|
919
|
+
# Fallback to regular LLM call with manual parsing
|
|
920
|
+
try:
|
|
921
|
+
# Calculate timeout using MessageManager
|
|
922
|
+
tool_count = len(self.controller.get_action_names()) if self.controller else 0
|
|
923
|
+
timeout_seconds = self.message_manager.calculate_llm_timeout(
|
|
924
|
+
tool_count=tool_count,
|
|
925
|
+
use_vision=self.use_vision
|
|
926
|
+
)
|
|
927
|
+
# Stream if supported and callbacks registered
|
|
928
|
+
_fb_start = time.time()
|
|
929
|
+
if self._supports_streaming() and self.hitl_manager.has_streaming_callbacks():
|
|
930
|
+
self.logger.debug("Using streaming mode for final fallback LLM call")
|
|
931
|
+
full_content = ""
|
|
932
|
+
fallback_usage_metadata = None # Initialize for fallback path
|
|
933
|
+
|
|
934
|
+
async def stream_with_timeout():
|
|
935
|
+
nonlocal full_content, fallback_usage_metadata
|
|
936
|
+
async for chunk in self.llm.astream(current_messages):
|
|
937
|
+
if hasattr(chunk, 'content') and chunk.content:
|
|
938
|
+
full_content += chunk.content
|
|
939
|
+
await self.hitl_manager.stream_output(chunk.content)
|
|
940
|
+
# Collect usage metadata from final chunk if available
|
|
941
|
+
if hasattr(chunk, 'usage_metadata') and chunk.usage_metadata:
|
|
942
|
+
fallback_usage_metadata = chunk.usage_metadata
|
|
943
|
+
|
|
944
|
+
await asyncio.wait_for(stream_with_timeout(), timeout=timeout_seconds)
|
|
945
|
+
response = AIMessage(content=full_content, usage_metadata=fallback_usage_metadata)
|
|
946
|
+
else:
|
|
947
|
+
response = await asyncio.wait_for(
|
|
948
|
+
self.llm.ainvoke(current_messages),
|
|
949
|
+
timeout=timeout_seconds
|
|
950
|
+
)
|
|
951
|
+
# G2: final manual-parse fallback completion must be billed too.
|
|
952
|
+
await self._bill_llm_response(response, time.time() - _fb_start, provider, purpose="next_action_fallback")
|
|
953
|
+
except asyncio.TimeoutError:
|
|
954
|
+
self.logger.error(f"LLM call timed out after {timeout_seconds} seconds", exc_info=True)
|
|
955
|
+
raise
|
|
956
|
+
parsed = None
|
|
957
|
+
|
|
958
|
+
# Handle manual parsing if structured output failed
|
|
959
|
+
if parsed is None:
|
|
960
|
+
self.logger.info("All structured methods failed - attempting manual JSON parsing")
|
|
961
|
+
# FIXED: More robust content extraction for different LLM response formats
|
|
962
|
+
content = None
|
|
963
|
+
|
|
964
|
+
# Try multiple ways to extract content from different response formats
|
|
965
|
+
if hasattr(response, 'content'):
|
|
966
|
+
# Standard response format
|
|
967
|
+
content = response.content
|
|
968
|
+
elif isinstance(response, dict):
|
|
969
|
+
# Dictionary response format
|
|
970
|
+
if 'content' in response:
|
|
971
|
+
content = response['content']
|
|
972
|
+
elif 'text' in response:
|
|
973
|
+
content = response['text']
|
|
974
|
+
elif 'message' in response and hasattr(response['message'], 'content'):
|
|
975
|
+
content = response['message'].content
|
|
976
|
+
elif 'generation_info' in response and 'raw' in response['generation_info']:
|
|
977
|
+
# Provider-specific raw payload
|
|
978
|
+
content = str(response['generation_info']['raw'])
|
|
979
|
+
elif isinstance(response, str):
|
|
980
|
+
# Direct string response
|
|
981
|
+
content = response
|
|
982
|
+
elif hasattr(response, 'text'):
|
|
983
|
+
# Alternative text attribute
|
|
984
|
+
content = response.text
|
|
985
|
+
elif hasattr(response, 'message') and hasattr(response.message, 'content'):
|
|
986
|
+
# Nested message structure
|
|
987
|
+
content = response.message.content
|
|
988
|
+
elif hasattr(response, 'generations') and len(response.generations) > 0:
|
|
989
|
+
# Generations format
|
|
990
|
+
gen = response.generations[0]
|
|
991
|
+
if hasattr(gen, 'message') and hasattr(gen.message, 'content'):
|
|
992
|
+
content = gen.message.content
|
|
993
|
+
elif hasattr(gen, 'text'):
|
|
994
|
+
content = gen.text
|
|
995
|
+
elif hasattr(response, 'additional_kwargs') and response.additional_kwargs:
|
|
996
|
+
# Check additional kwargs for content
|
|
997
|
+
if 'content' in response.additional_kwargs:
|
|
998
|
+
content = response.additional_kwargs['content']
|
|
999
|
+
elif 'raw' in response.additional_kwargs:
|
|
1000
|
+
content = str(response.additional_kwargs['raw'])
|
|
1001
|
+
|
|
1002
|
+
|
|
1003
|
+
# Normalize content to string (some providers return list)
|
|
1004
|
+
if content is not None and isinstance(content, list):
|
|
1005
|
+
content_parts = []
|
|
1006
|
+
for block in content:
|
|
1007
|
+
if isinstance(block, str):
|
|
1008
|
+
content_parts.append(block)
|
|
1009
|
+
elif hasattr(block, 'text'):
|
|
1010
|
+
content_parts.append(block.text)
|
|
1011
|
+
elif isinstance(block, dict) and 'text' in block:
|
|
1012
|
+
content_parts.append(block['text'])
|
|
1013
|
+
content = "".join(content_parts)
|
|
1014
|
+
|
|
1015
|
+
if content is not None and content.strip():
|
|
1016
|
+
try:
|
|
1017
|
+
# Direct JSON extraction using centralized utility
|
|
1018
|
+
# REFACTORED (Dec 2025): Removed duplicate preprocessing logic
|
|
1019
|
+
# normalize_action_schema now handles all action field corrections
|
|
1020
|
+
from agents.task.utils_json import (
|
|
1021
|
+
extract_json_from_model_output,
|
|
1022
|
+
normalize_action_schema,
|
|
1023
|
+
preprocess_action_data,
|
|
1024
|
+
apply_action_field_corrections
|
|
1025
|
+
)
|
|
1026
|
+
|
|
1027
|
+
extracted_json = extract_json_from_model_output(content)
|
|
1028
|
+
|
|
1029
|
+
# Handle single-action format (without 'action' wrapper)
|
|
1030
|
+
# This case is NOT handled by normalize_action_schema
|
|
1031
|
+
if extracted_json and isinstance(extracted_json, dict):
|
|
1032
|
+
if len(extracted_json) == 1 and not any(k in extracted_json for k in ['action', 'current_state', 'title', 'decision', 'confidence']):
|
|
1033
|
+
action_name, params = preprocess_action_data(extracted_json)
|
|
1034
|
+
params = apply_action_field_corrections(action_name, params)
|
|
1035
|
+
extracted_json = {'action': [{action_name: params}]}
|
|
1036
|
+
|
|
1037
|
+
# normalize_action_schema handles all action field corrections
|
|
1038
|
+
normalized_json = normalize_action_schema(extracted_json)
|
|
1039
|
+
|
|
1040
|
+
# AgentOutput requires 'action' field - LLM must always provide actions
|
|
1041
|
+
if 'action' not in normalized_json:
|
|
1042
|
+
self.logger.error("Normalized JSON missing 'action' field - LLM response invalid")
|
|
1043
|
+
self.logger.error("The LLM must provide actions in every response. Empty actions are not valid.")
|
|
1044
|
+
raise LLMResponseError("LLM response missing required 'action' field")
|
|
1045
|
+
|
|
1046
|
+
parsed = self.AgentOutput.model_validate(normalized_json)
|
|
1047
|
+
self.logger.info("Manual JSON extraction and validation succeeded")
|
|
1048
|
+
except Exception as extract_error:
|
|
1049
|
+
self.logger.error(f"Manual JSON extraction failed: {extract_error}", exc_info=True)
|
|
1050
|
+
self.logger.error(f"Full content that failed (first 2000 chars, exc_info=True): {content[:2000]}")
|
|
1051
|
+
raise LLMResponseError(f"Could not parse response: {str(extract_error)}")
|
|
1052
|
+
else:
|
|
1053
|
+
# Log the full response for debugging when no content is found
|
|
1054
|
+
self.logger.error(f"No content available for manual parsing. Response type: {type(response)}, Response: {str(response)[:1000]}", exc_info=True)
|
|
1055
|
+
raise LLMResponseError("No content available for manual parsing")
|
|
1056
|
+
|
|
1057
|
+
# Extract token usage and response metadata
|
|
1058
|
+
response_for_metadata = raw_tool_response if 'raw_tool_response' in locals() else response if 'response' in locals() else None
|
|
1059
|
+
|
|
1060
|
+
# Try to extract usage from AIMessage.additional_kwargs first (new method)
|
|
1061
|
+
token_usage = {}
|
|
1062
|
+
if response_for_metadata and hasattr(response_for_metadata, 'additional_kwargs'):
|
|
1063
|
+
usage_data = response_for_metadata.additional_kwargs.get('usage')
|
|
1064
|
+
if usage_data:
|
|
1065
|
+
token_usage = usage_data
|
|
1066
|
+
self.logger.debug(f"Extracted usage from AIMessage.additional_kwargs: {token_usage}")
|
|
1067
|
+
|
|
1068
|
+
# Fallback to old extraction method if no usage found
|
|
1069
|
+
if not token_usage or token_usage.get('total_tokens') is None:
|
|
1070
|
+
self.logger.debug("No usage in additional_kwargs, falling back to extract_token_usage")
|
|
1071
|
+
token_usage = extract_token_usage(response_for_metadata, provider)
|
|
1072
|
+
|
|
1073
|
+
total_tokens = token_usage.get("total_tokens")
|
|
1074
|
+
|
|
1075
|
+
# Extract model response metadata
|
|
1076
|
+
response_metadata = {}
|
|
1077
|
+
try:
|
|
1078
|
+
raw_resp = response_for_metadata.get('raw') if response_for_metadata and isinstance(response_for_metadata, dict) else response_for_metadata
|
|
1079
|
+
if raw_resp and hasattr(raw_resp, 'model'):
|
|
1080
|
+
response_metadata['model'] = raw_resp.model
|
|
1081
|
+
if raw_resp and hasattr(raw_resp, 'id'):
|
|
1082
|
+
response_metadata['response_id'] = raw_resp.id
|
|
1083
|
+
if raw_resp and hasattr(raw_resp, 'created'):
|
|
1084
|
+
response_metadata['created'] = raw_resp.created
|
|
1085
|
+
except Exception as e:
|
|
1086
|
+
self.logger.debug(f"Error extracting response metadata: {e}")
|
|
1087
|
+
|
|
1088
|
+
# Update request info with completion details
|
|
1089
|
+
elapsed_time = time.time() - start_time
|
|
1090
|
+
request_info.update({
|
|
1091
|
+
"elapsed_time": elapsed_time,
|
|
1092
|
+
"token_usage": token_usage,
|
|
1093
|
+
"response_metadata": response_metadata
|
|
1094
|
+
})
|
|
1095
|
+
|
|
1096
|
+
# Add request info to session data if available
|
|
1097
|
+
if hasattr(self, 'session_data'):
|
|
1098
|
+
if "llm_requests" not in self.session_data:
|
|
1099
|
+
self.session_data["llm_requests"] = []
|
|
1100
|
+
self.session_data["llm_requests"].append(request_info)
|
|
1101
|
+
|
|
1102
|
+
# CRITICAL FIX: Ensure parsed is always an AgentOutput object, never a dict
|
|
1103
|
+
if parsed is not None and not isinstance(parsed, self.AgentOutput):
|
|
1104
|
+
try:
|
|
1105
|
+
# If parsed is a dict, validate it into AgentOutput
|
|
1106
|
+
if isinstance(parsed, dict):
|
|
1107
|
+
self.logger.debug("Converting parsed dict to AgentOutput object")
|
|
1108
|
+
# Use centralized normalization for field name consistency
|
|
1109
|
+
normalized_dict = normalize_action_schema(parsed)
|
|
1110
|
+
parsed = self.AgentOutput.model_validate(normalized_dict)
|
|
1111
|
+
else:
|
|
1112
|
+
self.logger.warning(f"Unexpected parsed type: {type(parsed)}, attempting validation")
|
|
1113
|
+
parsed = self.AgentOutput.model_validate(parsed)
|
|
1114
|
+
except Exception as validation_error:
|
|
1115
|
+
self.logger.error(f"Failed to validate parsed response into AgentOutput: {validation_error}", exc_info=True)
|
|
1116
|
+
parsed = None
|
|
1117
|
+
last_error_type = "parse"
|
|
1118
|
+
|
|
1119
|
+
if parsed is None and RobustParseConfig.should_retry_parse_error(retry_count):
|
|
1120
|
+
# FIXED: Better retry logic with error type tracking
|
|
1121
|
+
retry_count += 1
|
|
1122
|
+
|
|
1123
|
+
delay = RobustParseConfig.get_exponential_backoff_delay(retry_count - 1)
|
|
1124
|
+
|
|
1125
|
+
self.logger.warning(f"Parse attempt {retry_count} failed, retrying in {delay:.1f}s")
|
|
1126
|
+
last_error = ValueError("Could not parse response")
|
|
1127
|
+
last_error_type = "parse"
|
|
1128
|
+
|
|
1129
|
+
await asyncio.sleep(delay)
|
|
1130
|
+
continue
|
|
1131
|
+
|
|
1132
|
+
if parsed is None:
|
|
1133
|
+
# FIX 8: Return safe default instead of raising error after MAX_PARSE_RETRIES
|
|
1134
|
+
self.logger.error('Could not parse response after all retry attempts, returning safe default', exc_info=True)
|
|
1135
|
+
# P0-5: AgentBrain requires evaluation_previous_goal/memory/next_goal —
|
|
1136
|
+
# a bare {"error": ...} dict raises ValidationError, so this "safe
|
|
1137
|
+
# default" actually re-raised and was reclassified as a parse error
|
|
1138
|
+
# (dead graceful-degradation path). Build a VALID brain instead.
|
|
1139
|
+
parsed = self.AgentOutput(
|
|
1140
|
+
current_state=AgentBrain(
|
|
1141
|
+
evaluation_previous_goal="Failed",
|
|
1142
|
+
memory="Previous LLM response could not be parsed after retries.",
|
|
1143
|
+
next_goal="Retry with a valid response.",
|
|
1144
|
+
reasoning="parse_failed: Failed to parse LLM response after retries",
|
|
1145
|
+
),
|
|
1146
|
+
action=[]
|
|
1147
|
+
)
|
|
1148
|
+
# Add parse failure telemetry
|
|
1149
|
+
if hasattr(self, 'session_data'):
|
|
1150
|
+
if 'parse_failures' not in self.session_data:
|
|
1151
|
+
self.session_data['parse_failures'] = []
|
|
1152
|
+
self.session_data['parse_failures'].append({
|
|
1153
|
+
'timestamp': time.time(),
|
|
1154
|
+
'model': self.model_name,
|
|
1155
|
+
'retry_count': retry_count
|
|
1156
|
+
})
|
|
1157
|
+
|
|
1158
|
+
# FINAL VALIDATION: Double-check that we have a proper AgentOutput object
|
|
1159
|
+
if not isinstance(parsed, self.AgentOutput):
|
|
1160
|
+
# FIX 8: Convert to safe default instead of raising
|
|
1161
|
+
self.logger.error(f'Parsed response is not an AgentOutput object, got: {type(parsed)}', exc_info=True)
|
|
1162
|
+
# P0-5: same fix — a valid AgentBrain, not a bare error dict.
|
|
1163
|
+
parsed = self.AgentOutput(
|
|
1164
|
+
current_state=AgentBrain(
|
|
1165
|
+
evaluation_previous_goal="Failed",
|
|
1166
|
+
memory=f"Parsed response had the wrong type ({type(parsed).__name__}); expected AgentOutput.",
|
|
1167
|
+
next_goal="Retry with a valid response.",
|
|
1168
|
+
reasoning="invalid_type: parser returned a non-AgentOutput object",
|
|
1169
|
+
),
|
|
1170
|
+
action=[]
|
|
1171
|
+
)
|
|
1172
|
+
|
|
1173
|
+
# NOTE: LLM telemetry is captured by usage_tracker.record_llm_usage() in the step loop
|
|
1174
|
+
# (see line ~3565). Do NOT add duplicate capture_llm_request() here as it causes
|
|
1175
|
+
# double counting in stats (50 steps → 100 LLM usage entries).
|
|
1176
|
+
|
|
1177
|
+
# Cut the number of actions to max_actions_per_step
|
|
1178
|
+
parsed.action = parsed.action[: self.max_actions_per_step]
|
|
1179
|
+
self._log_response(parsed)
|
|
1180
|
+
|
|
1181
|
+
# ============================================================================
|
|
1182
|
+
# NEW: POST-RESPONSE VISION VERIFICATION
|
|
1183
|
+
# ============================================================================
|
|
1184
|
+
if hasattr(self, '_expected_image_count') and self._expected_image_count > 0:
|
|
1185
|
+
# Extract response text
|
|
1186
|
+
response_text = ""
|
|
1187
|
+
if hasattr(response, 'content'):
|
|
1188
|
+
response_text = str(response.content)
|
|
1189
|
+
elif isinstance(response, dict) and 'parsed' in response:
|
|
1190
|
+
parsed_obj = response['parsed']
|
|
1191
|
+
if hasattr(parsed_obj, 'current_state'):
|
|
1192
|
+
brain_state = parsed_obj.current_state
|
|
1193
|
+
# Concatenate all brain state fields
|
|
1194
|
+
response_text = " ".join([
|
|
1195
|
+
str(getattr(brain_state, field, ""))
|
|
1196
|
+
for field in ['page_summary', 'memory', 'evaluation_previous_goal', 'next_goal', 'reasoning']
|
|
1197
|
+
if hasattr(brain_state, field)
|
|
1198
|
+
])
|
|
1199
|
+
else:
|
|
1200
|
+
response_text = str(response)
|
|
1201
|
+
|
|
1202
|
+
# ENHANCED VISION VERIFICATION: Three-layer check
|
|
1203
|
+
# Layer 0: NEGATIVE patterns (indicates failure - check first!)
|
|
1204
|
+
negative_keywords = [
|
|
1205
|
+
'cannot view', 'cannot analyze', 'cannot see', 'cannot directly',
|
|
1206
|
+
'unfortunately i cannot', 'unable to view', 'unable to analyze', 'not able to',
|
|
1207
|
+
'do not have access', 'cannot access', 'don\'t have access',
|
|
1208
|
+
'need a url', 'need to navigate', 'current interface',
|
|
1209
|
+
'through my interface', 'via browser', 'hosted online',
|
|
1210
|
+
'would need', 'could you please', 'share a web link',
|
|
1211
|
+
'provide a url', 'upload to', 'host the image'
|
|
1212
|
+
]
|
|
1213
|
+
has_negative = any(keyword in response_text.lower() for keyword in negative_keywords)
|
|
1214
|
+
|
|
1215
|
+
# Layer 1: Basic vision keywords (mentions images)
|
|
1216
|
+
vision_mention_keywords = [
|
|
1217
|
+
'image', 'picture', 'screenshot', 'visual', 'photo',
|
|
1218
|
+
'see', 'shown', 'displayed', 'appears', 'looks like',
|
|
1219
|
+
'in the image', 'from the screenshot', 'attached image'
|
|
1220
|
+
]
|
|
1221
|
+
mentions_vision = any(keyword in response_text.lower() for keyword in vision_mention_keywords)
|
|
1222
|
+
|
|
1223
|
+
# Layer 2: Actual visual description keywords (describes content)
|
|
1224
|
+
visual_description_keywords = [
|
|
1225
|
+
'shows', 'depicts', 'contains', 'features', 'displays',
|
|
1226
|
+
'color', 'colours', 'shape', 'button', 'field', 'layout', 'text',
|
|
1227
|
+
'positioned', 'aligned', 'centered', 'located', 'placed',
|
|
1228
|
+
'red', 'blue', 'green', 'white', 'black', 'background', 'foreground',
|
|
1229
|
+
'top', 'bottom', 'left', 'right', 'corner', 'center',
|
|
1230
|
+
'label', 'heading', 'icon', 'menu', 'section', 'panel'
|
|
1231
|
+
]
|
|
1232
|
+
has_description = any(keyword in response_text.lower() for keyword in visual_description_keywords)
|
|
1233
|
+
|
|
1234
|
+
# Check negative patterns FIRST (overrides everything else)
|
|
1235
|
+
if has_negative:
|
|
1236
|
+
matched_negatives = [kw for kw in negative_keywords if kw in response_text.lower()]
|
|
1237
|
+
self.logger.error(
|
|
1238
|
+
f"❌ VISION FAILURE (NEGATIVE PATTERN): LLM explicitly states inability to view images. "
|
|
1239
|
+
f"Matched patterns: {matched_negatives[:3]}\n"
|
|
1240
|
+
f"Root causes:\n"
|
|
1241
|
+
f" 1. Images did NOT reach the LLM (most likely - check upload timing)\n"
|
|
1242
|
+
f" 2. Message format error (multimodal content malformed)\n"
|
|
1243
|
+
f" 3. Session auto-started before files uploaded (WEBVIEW_AUTO_START_BUG)\n"
|
|
1244
|
+
f" Response preview: {response_text[:200]}..."
|
|
1245
|
+
)
|
|
1246
|
+
elif mentions_vision and has_description:
|
|
1247
|
+
self.logger.info(
|
|
1248
|
+
f"✅ VISION SUCCESS: LLM response contains actual visual analysis. "
|
|
1249
|
+
f"Images ({self._expected_image_count}) were processed correctly."
|
|
1250
|
+
)
|
|
1251
|
+
elif mentions_vision and not has_description:
|
|
1252
|
+
self.logger.warning(
|
|
1253
|
+
f"⚠️ VISION PARTIAL: Response mentions images but lacks detailed visual description. "
|
|
1254
|
+
f"Possible issues:\n"
|
|
1255
|
+
f" 1. LLM received images but chose not to describe them\n"
|
|
1256
|
+
f" 2. Images may be in wrong position relative to text (MESSAGE_ORDER_BUG)\n"
|
|
1257
|
+
f" 3. LLM confused about image context/workflow\n"
|
|
1258
|
+
f" Response preview: {response_text[:200]}..."
|
|
1259
|
+
)
|
|
1260
|
+
elif not mentions_vision and has_description:
|
|
1261
|
+
self.logger.info(
|
|
1262
|
+
f"✅ VISION SUCCESS: Response contains visual description despite no explicit mention. "
|
|
1263
|
+
f"Images ({self._expected_image_count}) likely processed."
|
|
1264
|
+
)
|
|
1265
|
+
else:
|
|
1266
|
+
# FIXED: Don't log ERROR for non-visual tasks
|
|
1267
|
+
# The LLM may correctly ignore screenshots when executing filesystem/tool tasks
|
|
1268
|
+
# Only log at DEBUG level since this is expected behavior for non-visual tasks
|
|
1269
|
+
self.logger.debug(
|
|
1270
|
+
f"📷 VISION SKIPPED: LLM response has no visual content ({self._expected_image_count} image(s) sent). "
|
|
1271
|
+
f"This is normal for non-visual tasks (filesystem ops, tool calls). "
|
|
1272
|
+
f"Response preview: {response_text[:100] if response_text else '(empty)'}..."
|
|
1273
|
+
)
|
|
1274
|
+
|
|
1275
|
+
# Clear the counter
|
|
1276
|
+
self._expected_image_count = 0
|
|
1277
|
+
# ============================================================================
|
|
1278
|
+
# END POST-RESPONSE VISION VERIFICATION
|
|
1279
|
+
# ============================================================================
|
|
1280
|
+
|
|
1281
|
+
# DEBUG: Log final parsed output
|
|
1282
|
+
|
|
1283
|
+
return parsed
|
|
1284
|
+
|
|
1285
|
+
except Exception as e:
|
|
1286
|
+
retry_count += 1
|
|
1287
|
+
last_error = e
|
|
1288
|
+
elapsed_time = time.time() - start_time
|
|
1289
|
+
|
|
1290
|
+
# FIXED: Better error type classification
|
|
1291
|
+
if "parse" in str(e).lower() or "json" in str(e).lower() or "validation" in str(e).lower():
|
|
1292
|
+
last_error_type = "parse"
|
|
1293
|
+
elif "rate" in str(e).lower() or "limit" in str(e).lower():
|
|
1294
|
+
last_error_type = "rate_limit"
|
|
1295
|
+
elif "llm_client" in str(e).lower():
|
|
1296
|
+
last_error_type = "parameter_error"
|
|
1297
|
+
else:
|
|
1298
|
+
last_error_type = "other"
|
|
1299
|
+
|
|
1300
|
+
self.logger.error(f"LLM request attempt {retry_count} failed after {elapsed_time:.2f}s: {str(e)}", exc_info=True)
|
|
1301
|
+
|
|
1302
|
+
# Update request info with error details
|
|
1303
|
+
request_info.update({
|
|
1304
|
+
"elapsed_time": elapsed_time,
|
|
1305
|
+
"error": str(e),
|
|
1306
|
+
"error_type": last_error_type
|
|
1307
|
+
})
|
|
1308
|
+
|
|
1309
|
+
# Add error request to session data if available
|
|
1310
|
+
if hasattr(self, 'session_data'):
|
|
1311
|
+
if "llm_requests" not in self.session_data:
|
|
1312
|
+
self.session_data["llm_requests"] = []
|
|
1313
|
+
self.session_data["llm_requests"].append(request_info)
|
|
1314
|
+
|
|
1315
|
+
# NOTE: LLM telemetry for failed requests is also captured by usage_tracker
|
|
1316
|
+
# in the step loop. Do NOT add duplicate capture_llm_request() here.
|
|
1317
|
+
|
|
1318
|
+
# Check if we should retry based on error type
|
|
1319
|
+
if RobustParseConfig.should_retry_parse_error(retry_count - 1) and last_error_type in ["parse", "rate_limit", "parameter_error"]:
|
|
1320
|
+
delay = RobustParseConfig.get_exponential_backoff_delay(retry_count - 1)
|
|
1321
|
+
self.logger.warning(f"Retrying LLM call in {delay:.1f}s (attempt {retry_count + 1}, error: {last_error_type})")
|
|
1322
|
+
await asyncio.sleep(delay)
|
|
1323
|
+
continue
|
|
1324
|
+
else:
|
|
1325
|
+
self.logger.error(f"LLM call failed after {retry_count} attempts", exc_info=True)
|
|
1326
|
+
raise
|
|
1327
|
+
|
|
1328
|
+
# Should not reach here, but just in case
|
|
1329
|
+
raise last_error or RuntimeError("LLM call failed after all retries")
|
|
1330
|
+
|
|
1331
|
+
|