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.
Files changed (745) hide show
  1. agents/README.md +453 -0
  2. agents/__init__.py +164 -0
  3. agents/base_agent.py +743 -0
  4. agents/personality/character.py +119 -0
  5. agents/personality/character_manager.py +309 -0
  6. agents/personality/characters/rob.character.json +56 -0
  7. agents/personality/characters/trump.character.json +63 -0
  8. agents/personality/persona_render.py +78 -0
  9. agents/personality/persona_resolver.py +115 -0
  10. agents/prompt/__init__.py +58 -0
  11. agents/prompt/base_prompt.py +92 -0
  12. agents/prompt/system.py +417 -0
  13. agents/task/README_PATH_MANAGEMENT.md +141 -0
  14. agents/task/__init__.py +162 -0
  15. agents/task/agent/__init__.py +70 -0
  16. agents/task/agent/agent_state.py +408 -0
  17. agents/task/agent/async_delegation.py +274 -0
  18. agents/task/agent/autonomy_state.py +275 -0
  19. agents/task/agent/conversation.py +75 -0
  20. agents/task/agent/core/__init__.py +6 -0
  21. agents/task/agent/core/aux_metering.py +61 -0
  22. agents/task/agent/core/background_review.py +157 -0
  23. agents/task/agent/core/construction.py +1179 -0
  24. agents/task/agent/core/conversational_exit.py +49 -0
  25. agents/task/agent/core/correspondent_gate.py +227 -0
  26. agents/task/agent/core/curator.py +246 -0
  27. agents/task/agent/core/episodic_digest.py +103 -0
  28. agents/task/agent/core/error_recovery.py +480 -0
  29. agents/task/agent/core/history_io.py +257 -0
  30. agents/task/agent/core/llm_provisioning.py +287 -0
  31. agents/task/agent/core/llm_runner.py +547 -0
  32. agents/task/agent/core/logging_io.py +276 -0
  33. agents/task/agent/core/loop_detection.py +262 -0
  34. agents/task/agent/core/memory_prefetch.py +325 -0
  35. agents/task/agent/core/memory_writer.py +667 -0
  36. agents/task/agent/core/model_introspection.py +82 -0
  37. agents/task/agent/core/model_swap.py +177 -0
  38. agents/task/agent/core/next_action_internal.py +1331 -0
  39. agents/task/agent/core/output_validation.py +303 -0
  40. agents/task/agent/core/project_context.py +272 -0
  41. agents/task/agent/core/resources.py +93 -0
  42. agents/task/agent/core/result_processing.py +389 -0
  43. agents/task/agent/core/run_loop.py +661 -0
  44. agents/task/agent/core/safety_lifecycle.py +228 -0
  45. agents/task/agent/core/secret_guard.py +293 -0
  46. agents/task/agent/core/self_wake.py +280 -0
  47. agents/task/agent/core/session_metadata.py +104 -0
  48. agents/task/agent/core/step.py +781 -0
  49. agents/task/agent/core/step_execution.py +398 -0
  50. agents/task/agent/core/step_telemetry.py +222 -0
  51. agents/task/agent/core/test_aux_metering.py +50 -0
  52. agents/task/agent/core/test_billing_failover.py +68 -0
  53. agents/task/agent/core/test_fatal_error_classifier.py +38 -0
  54. agents/task/agent/core/test_judge_validation.py +275 -0
  55. agents/task/agent/core/test_model_swap.py +190 -0
  56. agents/task/agent/core/test_reflection_offload.py +54 -0
  57. agents/task/agent/core/turn_input.py +8 -0
  58. agents/task/agent/core/untrusted_wrap.py +103 -0
  59. agents/task/agent/core/user_ingress.py +228 -0
  60. agents/task/agent/hitl_manager.py +396 -0
  61. agents/task/agent/log_sanitize.py +36 -0
  62. agents/task/agent/message_manager/config.py +97 -0
  63. agents/task/agent/message_manager/service.py +758 -0
  64. agents/task/agent/message_manager/tests.py +305 -0
  65. agents/task/agent/message_manager/tool_call_builder.py +539 -0
  66. agents/task/agent/message_manager/tool_message_repair.py +364 -0
  67. agents/task/agent/message_manager/views.py +143 -0
  68. agents/task/agent/messages/__init__.py +8 -0
  69. agents/task/agent/messages/builders.py +309 -0
  70. agents/task/agent/messages/compactor.py +611 -0
  71. agents/task/agent/messages/context_references.py +271 -0
  72. agents/task/agent/messages/filters.py +333 -0
  73. agents/task/agent/messages/guidance.py +328 -0
  74. agents/task/agent/messages/persistence.py +448 -0
  75. agents/task/agent/messages/retrieval.py +506 -0
  76. agents/task/agent/messages/sqlite_persistence.py +85 -0
  77. agents/task/agent/messages/test_compaction_upgrade.py +349 -0
  78. agents/task/agent/messages/test_persistence_subdir_fix.py +28 -0
  79. agents/task/agent/messages/test_sqlite_persistence.py +54 -0
  80. agents/task/agent/messages/token_counter.py +532 -0
  81. agents/task/agent/orchestrator.py +776 -0
  82. agents/task/agent/profile_manager.py +105 -0
  83. agents/task/agent/profile_registry.py +173 -0
  84. agents/task/agent/prompts.py +1090 -0
  85. agents/task/agent/scenario_registry.py +226 -0
  86. agents/task/agent/service.py +509 -0
  87. agents/task/agent/session.py +984 -0
  88. agents/task/agent/skill_discovery.py +110 -0
  89. agents/task/agent/skill_frontmatter.py +94 -0
  90. agents/task/agent/skill_manager.py +1201 -0
  91. agents/task/agent/skill_store.py +627 -0
  92. agents/task/agent/skill_validation.py +56 -0
  93. agents/task/agent/skill_writer.py +492 -0
  94. agents/task/agent/sub_agent_manager.py +1137 -0
  95. agents/task/agent/test_session_disk_recovery.py +34 -0
  96. agents/task/agent/tests.py +513 -0
  97. agents/task/agent/tool_call_tracker.py +511 -0
  98. agents/task/agent/views.py +469 -0
  99. agents/task/config.py +432 -0
  100. agents/task/constants.py +1384 -0
  101. agents/task/flag_defaults.py +63 -0
  102. agents/task/goals/__init__.py +1 -0
  103. agents/task/goals/autonomy_marker.py +28 -0
  104. agents/task/goals/board.py +690 -0
  105. agents/task/goals/completion_judge.py +247 -0
  106. agents/task/goals/context.py +62 -0
  107. agents/task/goals/dispatcher.py +848 -0
  108. agents/task/goals/escalation.py +102 -0
  109. agents/task/goals/planner.py +114 -0
  110. agents/task/logging_config.py +155 -0
  111. agents/task/path.py +991 -0
  112. agents/task/robust_parse_config.py +400 -0
  113. agents/task/runtime/__init__.py +0 -0
  114. agents/task/runtime/run_as_session.py +130 -0
  115. agents/task/runtime_safety.py +308 -0
  116. agents/task/session/__init__.py +5 -0
  117. agents/task/session/browser_pool.py +130 -0
  118. agents/task/session/cleanup.py +612 -0
  119. agents/task/session/execution.py +397 -0
  120. agents/task/session/feed.py +200 -0
  121. agents/task/session/hitl_ingress.py +201 -0
  122. agents/task/session/hooks.py +83 -0
  123. agents/task/session/multi_agent.py +243 -0
  124. agents/task/session/workspace.py +91 -0
  125. agents/task/session_registry.py +91 -0
  126. agents/task/session_route.py +35 -0
  127. agents/task/sqlite_session_registry.py +261 -0
  128. agents/task/surface_config.py +185 -0
  129. agents/task/telemetry/__init__.py +58 -0
  130. agents/task/telemetry/event_log.py +180 -0
  131. agents/task/telemetry/formatters.py +642 -0
  132. agents/task/telemetry/manager.py +571 -0
  133. agents/task/telemetry/memory_events.py +66 -0
  134. agents/task/telemetry/self_events.py +53 -0
  135. agents/task/telemetry/sequence.py +160 -0
  136. agents/task/telemetry/service.py +1265 -0
  137. agents/task/telemetry/views.py +882 -0
  138. agents/task/templates.py +98 -0
  139. agents/task/test_aux_chain.py +151 -0
  140. agents/task/test_aux_router.py +41 -0
  141. agents/task/tests/test_parse_robustness.py +170 -0
  142. agents/task/tool_defaults.py +110 -0
  143. agents/task/utils.py +762 -0
  144. agents/task/utils_json.py +768 -0
  145. agents/task/utils_webview.py +86 -0
  146. agents/task/workspace_context.py +229 -0
  147. agents/task_agent_lite.py +2398 -0
  148. api/README.md +683 -0
  149. api/TASK_API_DOCS.md +151 -0
  150. api/__init__.py +0 -0
  151. api/a2a/__init__.py +37 -0
  152. api/a2a/agent_card.py +337 -0
  153. api/a2a/client.py +657 -0
  154. api/a2a/endpoints.py +375 -0
  155. api/a2a/models.py +268 -0
  156. api/a2a/streaming.py +419 -0
  157. api/a2a/task_handler.py +929 -0
  158. api/admin_endpoints.py +1584 -0
  159. api/app.py +923 -0
  160. api/auth_constants.py +28 -0
  161. api/auth_endpoints.py +402 -0
  162. api/auth_state.py +36 -0
  163. api/chat_via_task.py +42 -0
  164. api/conversation_manager.py +231 -0
  165. api/dependencies.py +186 -0
  166. api/eip8004_endpoints.py +452 -0
  167. api/hyperliquid_models.py +174 -0
  168. api/hyperliquid_routes.py +450 -0
  169. api/interfaces.py +207 -0
  170. api/jwt_middleware.py +83 -0
  171. api/kb/__init__.py +1 -0
  172. api/kb/endpoints.py +314 -0
  173. api/mcp_models.py +279 -0
  174. api/mcp_routes.py +438 -0
  175. api/middleware.py +526 -0
  176. api/models.py +176 -0
  177. api/openai_compat/__init__.py +0 -0
  178. api/openai_compat/model_map.py +25 -0
  179. api/openai_compat/models.py +59 -0
  180. api/openai_compat/router.py +140 -0
  181. api/payment_endpoints.py +444 -0
  182. api/payment_verification.py +138 -0
  183. api/polymarket_models.py +155 -0
  184. api/polymarket_routes.py +501 -0
  185. api/pricing_endpoints.py +89 -0
  186. api/session_routing.py +54 -0
  187. api/skill_endpoints.py +453 -0
  188. api/task_http_api.py +1856 -0
  189. api/webhooks.py +52 -0
  190. api/x402_endpoints.py +280 -0
  191. avatar/README.md +44 -0
  192. avatar/__init__.py +1 -0
  193. avatar/config/rob.json +7 -0
  194. avatar/mindprint.js +395 -0
  195. avatar/renders/rob.meta.json +20 -0
  196. avatar/renders/rob.png +0 -0
  197. avatar/studio.html +373 -0
  198. avatar/webview/avatar-live.js +44 -0
  199. cli/README.md +89 -0
  200. cli/__init__.py +0 -0
  201. cli/cli_surface.py +67 -0
  202. cli/commands/__init__.py +0 -0
  203. cli/commands/_bootstrap.py +49 -0
  204. cli/commands/_errors.py +53 -0
  205. cli/commands/chat.py +973 -0
  206. cli/commands/config.py +100 -0
  207. cli/commands/dashboard.py +103 -0
  208. cli/commands/doctor.py +222 -0
  209. cli/commands/email.py +174 -0
  210. cli/commands/gateway.py +346 -0
  211. cli/commands/goals.py +509 -0
  212. cli/commands/init.py +276 -0
  213. cli/commands/journey.py +30 -0
  214. cli/commands/kb.py +280 -0
  215. cli/commands/model.py +107 -0
  216. cli/commands/owner.py +431 -0
  217. cli/commands/pfp.py +232 -0
  218. cli/commands/run.py +414 -0
  219. cli/commands/serve.py +41 -0
  220. cli/commands/session.py +684 -0
  221. cli/commands/skill_install.py +786 -0
  222. cli/commands/skills.py +128 -0
  223. cli/commands/subagents.py +100 -0
  224. cli/commands/surface.py +81 -0
  225. cli/commands/telegram.py +185 -0
  226. cli/commands/todos.py +209 -0
  227. cli/commands/tools.py +102 -0
  228. cli/commands/update.py +316 -0
  229. cli/commands/whatsapp.py +175 -0
  230. cli/config_store.py +276 -0
  231. cli/gitignore.py +43 -0
  232. cli/inventory.py +46 -0
  233. cli/keys.py +101 -0
  234. cli/persona.py +17 -0
  235. cli/polyrob.py +137 -0
  236. cli/ui/__init__.py +64 -0
  237. cli/ui/activity.py +141 -0
  238. cli/ui/app.py +538 -0
  239. cli/ui/banner.py +233 -0
  240. cli/ui/blocks.py +534 -0
  241. cli/ui/bootstrap_notice.py +47 -0
  242. cli/ui/commands/__init__.py +41 -0
  243. cli/ui/commands/h_cron.py +64 -0
  244. cli/ui/commands/h_journey.py +164 -0
  245. cli/ui/commands/h_kb.py +121 -0
  246. cli/ui/commands/h_learn.py +100 -0
  247. cli/ui/commands/h_mcp.py +215 -0
  248. cli/ui/commands/h_self.py +113 -0
  249. cli/ui/commands/h_skills.py +314 -0
  250. cli/ui/commands/handlers.py +1672 -0
  251. cli/ui/commands/registry.py +426 -0
  252. cli/ui/dialog.py +425 -0
  253. cli/ui/event_registry.py +110 -0
  254. cli/ui/event_specs.py +45 -0
  255. cli/ui/events.py +433 -0
  256. cli/ui/identity.py +15 -0
  257. cli/ui/lifecycle.py +159 -0
  258. cli/ui/live_hooks.py +43 -0
  259. cli/ui/model_selector.py +532 -0
  260. cli/ui/persistent_loop.py +181 -0
  261. cli/ui/pick.py +113 -0
  262. cli/ui/plain_renderer.py +351 -0
  263. cli/ui/renderer.py +384 -0
  264. cli/ui/rich_renderer.py +533 -0
  265. cli/ui/secrets.py +115 -0
  266. cli/ui/state.py +376 -0
  267. cli/ui/statusbar.py +231 -0
  268. cli/ui/streaming.py +254 -0
  269. cli/ui/terminal_render.py +105 -0
  270. cli/ui/theme.py +132 -0
  271. cli/update/__init__.py +6 -0
  272. cli/update/context.py +121 -0
  273. cli/update/detect.py +176 -0
  274. cli/update/engine.py +95 -0
  275. cli/update/migrate_guarded.py +55 -0
  276. cli/update/process_guard.py +215 -0
  277. cli/update/runners.py +78 -0
  278. cli/update/snapshot.py +270 -0
  279. cli/update/versions.py +205 -0
  280. core/README.md +377 -0
  281. core/__init__.py +174 -0
  282. core/assets.py +87 -0
  283. core/async_bridge.py +76 -0
  284. core/autonomy_runtime.py +259 -0
  285. core/base_component.py +302 -0
  286. core/bootstrap.py +681 -0
  287. core/bot.py +310 -0
  288. core/config.py +833 -0
  289. core/constants.py +126 -0
  290. core/container.py +462 -0
  291. core/db_manifest.py +101 -0
  292. core/embedding.py +57 -0
  293. core/env.py +39 -0
  294. core/exceptions.py +287 -0
  295. core/flags.py +144 -0
  296. core/flags_catalog.py +345 -0
  297. core/home_migration.py +62 -0
  298. core/identity.py +118 -0
  299. core/initialization.py +1004 -0
  300. core/instance.py +537 -0
  301. core/interactive_gate.py +96 -0
  302. core/logging.py +436 -0
  303. core/owner_doc_writer.py +176 -0
  304. core/pairing.py +193 -0
  305. core/path_safety.py +20 -0
  306. core/paths.py +27 -0
  307. core/payment_config.py +21 -0
  308. core/permissions.py +322 -0
  309. core/runtime_config.py +96 -0
  310. core/runtime_paths.py +135 -0
  311. core/seams.py +35 -0
  312. core/secret_scan.py +25 -0
  313. core/secret_scrub.py +71 -0
  314. core/secrets.py +35 -0
  315. core/security_logging_filter.py +148 -0
  316. core/self_context_writer.py +333 -0
  317. core/self_evolution.py +294 -0
  318. core/session_context.py +47 -0
  319. core/sqlite_util.py +59 -0
  320. core/surfaces/__init__.py +16 -0
  321. core/surfaces/access.py +118 -0
  322. core/surfaces/binding.py +88 -0
  323. core/surfaces/bootstrap.py +78 -0
  324. core/surfaces/circuit.py +168 -0
  325. core/surfaces/continuity.py +77 -0
  326. core/surfaces/correspondents.py +228 -0
  327. core/surfaces/dispatcher.py +216 -0
  328. core/surfaces/envelopes.py +75 -0
  329. core/surfaces/gc.py +30 -0
  330. core/surfaces/idempotency.py +57 -0
  331. core/surfaces/inbound_webhook.py +124 -0
  332. core/surfaces/media.py +32 -0
  333. core/surfaces/message_router.py +91 -0
  334. core/surfaces/outbound_allowlist.py +80 -0
  335. core/surfaces/outbound_dispatcher.py +110 -0
  336. core/surfaces/outbound_mirror.py +37 -0
  337. core/surfaces/outbound_queue.py +107 -0
  338. core/surfaces/outbound_target.py +12 -0
  339. core/surfaces/owner_admin.py +29 -0
  340. core/surfaces/proactive.py +78 -0
  341. core/surfaces/progress.py +108 -0
  342. core/surfaces/rate_bucket.py +21 -0
  343. core/surfaces/registry.py +51 -0
  344. core/surfaces/rendering.py +53 -0
  345. core/surfaces/send_policy.py +14 -0
  346. core/surfaces/serialize.py +24 -0
  347. core/surfaces/session_chat_registry.py +112 -0
  348. core/surfaces/session_policy.py +60 -0
  349. core/surfaces/surface.py +288 -0
  350. core/surfaces/transcription.py +88 -0
  351. core/surfaces/voice_echo.py +26 -0
  352. core/surfaces/voice_guard.py +23 -0
  353. core/tickers.py +174 -0
  354. core/tool_catalog.py +192 -0
  355. core/version.py +75 -0
  356. core/wallet/__init__.py +5 -0
  357. core/wallet/agent_wallet.py +59 -0
  358. core/wallet/audit_sink.py +61 -0
  359. core/wallet/config.py +70 -0
  360. core/wallet/factory.py +87 -0
  361. core/wallet/policy.py +104 -0
  362. core/wallet/signer.py +51 -0
  363. cron/README.md +65 -0
  364. cron/__init__.py +0 -0
  365. cron/delivery.py +277 -0
  366. cron/digest.py +124 -0
  367. cron/jobs.py +207 -0
  368. cron/runner.py +297 -0
  369. cron/schedule.py +194 -0
  370. cron/scheduler.py +201 -0
  371. cron/service.py +57 -0
  372. cron/wake_gate.py +223 -0
  373. data/__init__.py +1 -0
  374. data/prompts/autov2_prompts.json +87 -0
  375. data/prompts/skills/browser-automation/SKILL.md +43 -0
  376. data/prompts/skills/coding-workflow/SKILL.md +36 -0
  377. data/prompts/skills/crypto-trading-safety/SKILL.md +53 -0
  378. data/prompts/skills/document-writing/SKILL.md +33 -0
  379. data/prompts/skills/email-comms/SKILL.md +33 -0
  380. data/prompts/skills/file-data-ops/SKILL.md +35 -0
  381. data/prompts/skills/hyperliquid-account-review/SKILL.md +48 -0
  382. data/prompts/skills/hyperliquid-market-data/SKILL.md +52 -0
  383. data/prompts/skills/hyperliquid-trading/SKILL.md +59 -0
  384. data/prompts/skills/lead-research/SKILL.md +86 -0
  385. data/prompts/skills/market-research-brief/SKILL.md +104 -0
  386. data/prompts/skills/person-analyzer/SKILL.md +124 -0
  387. data/prompts/skills/polymarket-market-research/SKILL.md +54 -0
  388. data/prompts/skills/polymarket-portfolio-review/SKILL.md +50 -0
  389. data/prompts/skills/polymarket-trading/SKILL.md +55 -0
  390. data/prompts/skills/presentation-creator/SKILL.md +36 -0
  391. data/prompts/skills/project-analyzer/SKILL.md +169 -0
  392. data/prompts/skills/rules.json +268 -0
  393. data/prompts/skills/secret-handling/SKILL.md +20 -0
  394. data/prompts/skills/skill-authoring/SKILL.md +31 -0
  395. data/prompts/skills/skill-security-review/SKILL.md +27 -0
  396. data/prompts/skills/social-discovery/SKILL.md +57 -0
  397. data/prompts/skills/task-planning/SKILL.md +33 -0
  398. data/prompts/skills/web-research/SKILL.md +39 -0
  399. data/prompts/skills/web-scraping/SKILL.md +73 -0
  400. data/prompts/skills/x-engagement/SKILL.md +69 -0
  401. data/prompts/system_prompts.json +4 -0
  402. data/subscription_channels.json +5 -0
  403. modules/README.md +503 -0
  404. modules/__init__.py +124 -0
  405. modules/auth/__init__.py +13 -0
  406. modules/auth/api_key_manager.py +157 -0
  407. modules/auth/identity_mapper.py +380 -0
  408. modules/auth/siwe_auth.py +273 -0
  409. modules/auth/tier_manager.py +173 -0
  410. modules/base_module.py +190 -0
  411. modules/credits/__init__.py +29 -0
  412. modules/credits/balance_manager.py +237 -0
  413. modules/credits/cost_utils.py +129 -0
  414. modules/credits/pricing.py +139 -0
  415. modules/credits/unified_ledger.py +148 -0
  416. modules/credits/usage_meter.py +310 -0
  417. modules/credits/usage_tracker.py +674 -0
  418. modules/database/__init__.py +33 -0
  419. modules/database/audit_log.py +322 -0
  420. modules/database/auth_tables.py +276 -0
  421. modules/database/connection.py +644 -0
  422. modules/database/connection_pool.py +305 -0
  423. modules/database/conversation_contexts.py +446 -0
  424. modules/database/database_manager.py +237 -0
  425. modules/database/hyperliquid.py +375 -0
  426. modules/database/polymarket.py +574 -0
  427. modules/database/user_mcp_servers.py +728 -0
  428. modules/database/user_profiles.py +562 -0
  429. modules/database/utils.py +107 -0
  430. modules/database/x402_tables.py +92 -0
  431. modules/eip8004/README.md +1069 -0
  432. modules/eip8004/__init__.py +65 -0
  433. modules/eip8004/contracts.py +498 -0
  434. modules/eip8004/models.py +271 -0
  435. modules/eip8004/registration.py +148 -0
  436. modules/eip8004/reputation.py +367 -0
  437. modules/eip8004/validation.py +277 -0
  438. modules/llm/__init__.py +97 -0
  439. modules/llm/adapters.py +963 -0
  440. modules/llm/anthropic_client.py +831 -0
  441. modules/llm/available_models.py +106 -0
  442. modules/llm/brain_scrubber.py +137 -0
  443. modules/llm/cache_hints.py +162 -0
  444. modules/llm/deepseek_client.py +562 -0
  445. modules/llm/gemini_client.py +1367 -0
  446. modules/llm/llm_client.py +1139 -0
  447. modules/llm/llm_client_registry.py +188 -0
  448. modules/llm/llm_factory.py +237 -0
  449. modules/llm/llm_manager.py +1036 -0
  450. modules/llm/messages.py +374 -0
  451. modules/llm/model_registry.py +1935 -0
  452. modules/llm/nvidia_client.py +125 -0
  453. modules/llm/openai_client.py +800 -0
  454. modules/llm/openrouter_client.py +969 -0
  455. modules/llm/profiles.py +178 -0
  456. modules/llm/test_anthropic_cache_capture.py +35 -0
  457. modules/llm/test_cached_pricing_derivation.py +24 -0
  458. modules/llm/think_scrubber.py +444 -0
  459. modules/llm/token_counter.py +268 -0
  460. modules/memory/__init__.py +35 -0
  461. modules/memory/backend_factory.py +83 -0
  462. modules/memory/cache_manager.py +186 -0
  463. modules/memory/episodic.py +108 -0
  464. modules/memory/local_vector_memory_provider.py +552 -0
  465. modules/memory/memory_manager.py +225 -0
  466. modules/memory/models.py +312 -0
  467. modules/memory/provider.py +210 -0
  468. modules/memory/registry.py +205 -0
  469. modules/memory/sqlite_memory_provider.py +767 -0
  470. modules/memory/task/__init__.py +52 -0
  471. modules/memory/task/compaction_manager.py +157 -0
  472. modules/memory/task/context_retriever.py +809 -0
  473. modules/memory/task/hierarchical_memory.py +1002 -0
  474. modules/memory/task/lexical_retriever.py +71 -0
  475. modules/memory/task/null_context_manager.py +213 -0
  476. modules/memory/task/phase_manager.py +625 -0
  477. modules/memory/task/reflection_service.py +157 -0
  478. modules/memory/task/semantic_retriever.py +218 -0
  479. modules/memory/task/task_context_manager.py +1165 -0
  480. modules/memory/task/test_forgetting_engages.py +24 -0
  481. modules/memory/task/test_reflection_llm.py +39 -0
  482. modules/memory/task/test_threat_scan.py +53 -0
  483. modules/memory/task/threat_scan.py +90 -0
  484. modules/memory/test_sqlite_memory_provider.py +106 -0
  485. modules/memory/user_profile_manager.py +527 -0
  486. modules/payments/__init__.py +11 -0
  487. modules/payments/deposit_monitor.py +478 -0
  488. modules/payments/price_oracle.py +70 -0
  489. modules/payments/treasury_sweeper.py +401 -0
  490. modules/payments/wallet_generator.py +145 -0
  491. modules/pfp/__init__.py +1 -0
  492. modules/pfp/config.py +92 -0
  493. modules/pfp/mesh.py +565 -0
  494. modules/pfp/push.py +69 -0
  495. modules/pfp/renderer.py +85 -0
  496. modules/pfp/store.py +82 -0
  497. modules/skills/__init__.py +1 -0
  498. modules/skills/skill_usage.py +248 -0
  499. modules/transcription/__init__.py +24 -0
  500. modules/transcription/base.py +20 -0
  501. modules/transcription/faster_whisper_transcriber.py +55 -0
  502. modules/x402/README.md +249 -0
  503. modules/x402/__init__.py +22 -0
  504. modules/x402/invoicing.py +416 -0
  505. modules/x402/middleware.py +364 -0
  506. modules/x402/settlement_watcher.py +145 -0
  507. modules/x402/x402_integration.py +344 -0
  508. polyrob-0.5.0.dist-info/METADATA +482 -0
  509. polyrob-0.5.0.dist-info/RECORD +745 -0
  510. polyrob-0.5.0.dist-info/WHEEL +5 -0
  511. polyrob-0.5.0.dist-info/entry_points.txt +2 -0
  512. polyrob-0.5.0.dist-info/licenses/LICENSE +21 -0
  513. polyrob-0.5.0.dist-info/top_level.txt +12 -0
  514. surfaces/README.md +70 -0
  515. surfaces/__init__.py +0 -0
  516. surfaces/email/__init__.py +0 -0
  517. surfaces/email/dedup.py +44 -0
  518. surfaces/email/harness.py +187 -0
  519. surfaces/email/inbound.py +159 -0
  520. surfaces/email/seed.py +60 -0
  521. surfaces/email/surface.py +105 -0
  522. surfaces/telegram/__init__.py +0 -0
  523. surfaces/telegram/dedup.py +83 -0
  524. surfaces/telegram/harness.py +886 -0
  525. surfaces/telegram/inbound.py +145 -0
  526. surfaces/telegram/interactive_tools.py +49 -0
  527. surfaces/telegram/markdown.py +347 -0
  528. surfaces/telegram/rate_limit.py +167 -0
  529. surfaces/telegram/surface.py +187 -0
  530. surfaces/telegram/voice.py +52 -0
  531. surfaces/whatsapp/__init__.py +0 -0
  532. surfaces/whatsapp/client.py +51 -0
  533. surfaces/whatsapp/harness.py +62 -0
  534. surfaces/whatsapp/inbound.py +132 -0
  535. surfaces/whatsapp/surface.py +64 -0
  536. surfaces/whatsapp/window.py +34 -0
  537. tools/README.md +578 -0
  538. tools/__init__.py +424 -0
  539. tools/alchemy/__init__.py +5 -0
  540. tools/alchemy/alchemy_tool.py +389 -0
  541. tools/anysite/__init__.py +17 -0
  542. tools/anysite/client.py +88 -0
  543. tools/anysite/tool.py +89 -0
  544. tools/base_tool.py +468 -0
  545. tools/browser/__init__.py +22 -0
  546. tools/browser/actions.py +118 -0
  547. tools/browser/browser.py +1457 -0
  548. tools/browser/browser_manager.py +690 -0
  549. tools/browser/context.py +1748 -0
  550. tools/browser/playwright_utils.py +137 -0
  551. tools/browser/views.py +56 -0
  552. tools/code_exec/SANDBOX_SECURITY.md +144 -0
  553. tools/code_exec/__init__.py +178 -0
  554. tools/code_exec/backend.py +73 -0
  555. tools/code_exec/backends/__init__.py +1 -0
  556. tools/code_exec/backends/docker.py +779 -0
  557. tools/code_exec/backends/local_subprocess.py +154 -0
  558. tools/code_exec/env_policy.py +45 -0
  559. tools/code_exec/result.py +42 -0
  560. tools/code_exec/sandbox_guard.py +59 -0
  561. tools/code_exec/tool.py +227 -0
  562. tools/coding/__init__.py +50 -0
  563. tools/coding/edit.py +107 -0
  564. tools/coding/search.py +113 -0
  565. tools/coding/tool.py +353 -0
  566. tools/collabland/__init__.py +5 -0
  567. tools/collabland/collabland_tool.py +471 -0
  568. tools/controller/__init__.py +0 -0
  569. tools/controller/_helpers.py +165 -0
  570. tools/controller/action_registration.py +1765 -0
  571. tools/controller/approval.py +244 -0
  572. tools/controller/approval_interactive.py +90 -0
  573. tools/controller/delegation.py +195 -0
  574. tools/controller/execution.py +797 -0
  575. tools/controller/execution_context.py +141 -0
  576. tools/controller/hooks.py +135 -0
  577. tools/controller/introspection.py +344 -0
  578. tools/controller/mcp_registrar.py +190 -0
  579. tools/controller/message_send.py +31 -0
  580. tools/controller/registry/__init__.py +4 -0
  581. tools/controller/registry/schema_generators.py +395 -0
  582. tools/controller/registry/schema_sanitizer.py +406 -0
  583. tools/controller/registry/service.py +1266 -0
  584. tools/controller/registry/views.py +151 -0
  585. tools/controller/service.py +409 -0
  586. tools/controller/tool_management.py +334 -0
  587. tools/controller/types.py +28 -0
  588. tools/controller/views.py +450 -0
  589. tools/cronjob_tools.py +166 -0
  590. tools/crypto_trade_gate.py +59 -0
  591. tools/descriptors.py +452 -0
  592. tools/dom/__init__.py +0 -0
  593. tools/dom/history_tree_processor/service.py +244 -0
  594. tools/dom/history_tree_processor/view.py +99 -0
  595. tools/dom/service.py +471 -0
  596. tools/dom/views.py +346 -0
  597. tools/email_tool.py +403 -0
  598. tools/exceptions.py +169 -0
  599. tools/filesystem.py +1038 -0
  600. tools/filesystem_docproc.py +331 -0
  601. tools/filesystem_pdf.py +755 -0
  602. tools/git/__init__.py +42 -0
  603. tools/git/tool.py +258 -0
  604. tools/github/__init__.py +33 -0
  605. tools/github/client.py +94 -0
  606. tools/github/tool.py +237 -0
  607. tools/goal_tools.py +309 -0
  608. tools/hyperliquid/__init__.py +56 -0
  609. tools/hyperliquid/models.py +233 -0
  610. tools/hyperliquid/service.py +1680 -0
  611. tools/knowledge_ingest.py +950 -0
  612. tools/mcp/README.md +535 -0
  613. tools/mcp/__init__.py +52 -0
  614. tools/mcp/catalog.py +115 -0
  615. tools/mcp/config.py +337 -0
  616. tools/mcp/mcp_tool.py +1415 -0
  617. tools/mcp/param_coercion.py +289 -0
  618. tools/mcp/protocol.py +1520 -0
  619. tools/mcp/rate_limit.py +50 -0
  620. tools/mcp/security.py +424 -0
  621. tools/mcp/self_install.py +111 -0
  622. tools/mcp/server_manager.py +829 -0
  623. tools/mcp/subscriptions.py +72 -0
  624. tools/mcp/user_mcp_service.py +899 -0
  625. tools/mcp/validation_tracker.py +89 -0
  626. tools/mcp/views.py +346 -0
  627. tools/oauth/__init__.py +17 -0
  628. tools/oauth/manager.py +75 -0
  629. tools/oauth/provider.py +69 -0
  630. tools/oauth/providers/__init__.py +1 -0
  631. tools/oauth/providers/generic_oauth2.py +96 -0
  632. tools/perplexity_tool.py +280 -0
  633. tools/polymarket/__init__.py +41 -0
  634. tools/polymarket/clob_adapter.py +76 -0
  635. tools/polymarket/models.py +182 -0
  636. tools/polymarket/service.py +2082 -0
  637. tools/self_env/__init__.py +61 -0
  638. tools/self_env/tool.py +274 -0
  639. tools/shell/__init__.py +80 -0
  640. tools/shell/backend_pool.py +118 -0
  641. tools/shell/discipline.py +62 -0
  642. tools/shell/executor.py +157 -0
  643. tools/shell/loopback_allow.py +87 -0
  644. tools/shell/process_registry.py +113 -0
  645. tools/shell/process_tool.py +131 -0
  646. tools/shell/state.py +129 -0
  647. tools/shell/tool.py +151 -0
  648. tools/task_tool.py +637 -0
  649. tools/twitter_tool.py +2086 -0
  650. tools/user_directory.py +179 -0
  651. tools/web_fetch/__init__.py +3 -0
  652. tools/web_fetch/fetcher.py +144 -0
  653. tools/web_fetch/render.py +44 -0
  654. tools/web_fetch/tool.py +60 -0
  655. tools/x402/__init__.py +60 -0
  656. tools/x402/client.py +47 -0
  657. tools/x402/invoice_tool.py +143 -0
  658. tools/x402/real_client.py +250 -0
  659. tools/x402/service.py +131 -0
  660. utils/README.md +498 -0
  661. utils/__init__.py +46 -0
  662. utils/auth_utils.py +114 -0
  663. utils/bounded_collections.py +162 -0
  664. utils/circuit_breaker.py +389 -0
  665. utils/gif_utils.py +435 -0
  666. utils/markdown_utils.py +291 -0
  667. utils/message_utils.py +147 -0
  668. utils/metrics.py +36 -0
  669. utils/path_validator.py +227 -0
  670. utils/rate_limit_manager.py +399 -0
  671. utils/result_size.py +296 -0
  672. utils/time_utils.py +206 -0
  673. utils/user_utils.py +188 -0
  674. webview/README.md +111 -0
  675. webview/RENAME_AND_ALIGN_HANDOFF.md +200 -0
  676. webview/__init__.py +8 -0
  677. webview/activity.py +636 -0
  678. webview/owner_auth.py +108 -0
  679. webview/pages.py +448 -0
  680. webview/repair_sessions.py +399 -0
  681. webview/server.py +4323 -0
  682. webview/server_launcher.py +112 -0
  683. webview/static/css/activity.css +89 -0
  684. webview/static/css/chat.css +1772 -0
  685. webview/static/css/components.css +1190 -0
  686. webview/static/css/config-panel.css +651 -0
  687. webview/static/css/pages/admin.css +766 -0
  688. webview/static/css/pages/profile.css +231 -0
  689. webview/static/css/pages/settings.css +297 -0
  690. webview/static/css/pages/signin.css +316 -0
  691. webview/static/css/style.css +4250 -0
  692. webview/static/css/variables.css +147 -0
  693. webview/static/css/workspace-fullwidth-fix.css +109 -0
  694. webview/static/img/favicon.ico +0 -0
  695. webview/static/js/activity.js +394 -0
  696. webview/static/js/admin/activity.js +186 -0
  697. webview/static/js/admin/dashboard.js +163 -0
  698. webview/static/js/admin/user_detail.js +400 -0
  699. webview/static/js/admin/users.js +174 -0
  700. webview/static/js/admin/utils.js +214 -0
  701. webview/static/js/chat.js +3178 -0
  702. webview/static/js/config-panel.js +522 -0
  703. webview/static/js/constants.js +20 -0
  704. webview/static/js/error-handler.js +226 -0
  705. webview/static/js/ethers.min.js +1 -0
  706. webview/static/js/event-filter.js +137 -0
  707. webview/static/js/event-store.js +351 -0
  708. webview/static/js/file-attachments.js +374 -0
  709. webview/static/js/file-loader.js +163 -0
  710. webview/static/js/index.js +103 -0
  711. webview/static/js/performance-utils.js +196 -0
  712. webview/static/js/profile.js +396 -0
  713. webview/static/js/screenshot.js +386 -0
  714. webview/static/js/session.js +1527 -0
  715. webview/static/js/settings.js +1288 -0
  716. webview/static/js/sidebar-data.js +766 -0
  717. webview/static/js/sidebar-toggle.js +296 -0
  718. webview/static/js/socket.io.min.js +7 -0
  719. webview/static/js/stats.js +355 -0
  720. webview/static/js/ui-utils.js +420 -0
  721. webview/static/js/workspace.js +966 -0
  722. webview/stats_service.py +613 -0
  723. webview/templates/__init__.py +1 -0
  724. webview/templates/__pycache__/__init__.cpython-311.pyc +0 -0
  725. webview/templates/activity.html +36 -0
  726. webview/templates/admin/activity.html +122 -0
  727. webview/templates/admin/dashboard.html +112 -0
  728. webview/templates/admin/user_detail.html +228 -0
  729. webview/templates/admin/users.html +105 -0
  730. webview/templates/autonomy.html +60 -0
  731. webview/templates/error.html +133 -0
  732. webview/templates/finance.html +90 -0
  733. webview/templates/identity.html +73 -0
  734. webview/templates/index.html +42 -0
  735. webview/templates/layout.html +125 -0
  736. webview/templates/memory.html +59 -0
  737. webview/templates/owner_login.html +15 -0
  738. webview/templates/profile.html +121 -0
  739. webview/templates/session.html +312 -0
  740. webview/templates/settings.html +534 -0
  741. webview/templates/sidebar.html +112 -0
  742. webview/templates/signin.html +213 -0
  743. webview/templates/status.html +14 -0
  744. webview/templates/system.html +45 -0
  745. 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
+