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,831 @@
1
+ """Anthropic Claude API Client."""
2
+
3
+ import json
4
+ import logging
5
+ import asyncio
6
+ import time
7
+ from typing import List, Dict, Any, Optional, Union, Tuple
8
+
9
+ import anthropic
10
+ from anthropic.types import ContentBlock, MessageParam, Message
11
+
12
+ from modules.llm.llm_client import LLMClient
13
+ from modules.llm.token_counter import count_messages_tokens
14
+ from core.exceptions import LLMError, LLMConfigError, LLMRateLimitError, LLMAuthenticationError, LLMContextLengthError, LLMInvalidRequestError, LLMConnectionError, ServiceError
15
+ from core.config import BotConfig
16
+ import os
17
+
18
+ # Import default model from registry
19
+ from modules.llm.llm_client_registry import get_default_model
20
+
21
+
22
+ def _clamp_thinking(model_cap, budget, current_max_tokens):
23
+ """H4: return (budget, max_tokens) valid for Anthropic extended thinking.
24
+
25
+ Anthropic requires ``max_tokens > thinking.budget_tokens`` AND
26
+ ``max_tokens <= the model's real completion cap``. Registry entries set
27
+ budget == cap, so the old ``max_tokens = budget + 4096`` overran the cap and 400'd.
28
+ Shrink the budget to leave >=4096 output room under the cap; if the cap is too
29
+ small to fit any thinking, return (None, ...) so the caller disables thinking.
30
+ """
31
+ if not budget or budget <= 0:
32
+ return None, current_max_tokens
33
+ if model_cap and model_cap > 0:
34
+ max_budget = model_cap - 4096
35
+ if max_budget < 1024:
36
+ # Cap too small to fit thinking + output room — disable thinking.
37
+ return None, min(current_max_tokens, model_cap)
38
+ if budget > max_budget:
39
+ budget = max_budget
40
+ max_tokens = current_max_tokens
41
+ if max_tokens <= budget:
42
+ max_tokens = budget + 4096
43
+ max_tokens = min(max_tokens, model_cap)
44
+ return budget, max_tokens
45
+ # No cap known — preserve legacy behaviour (bump above budget).
46
+ max_tokens = current_max_tokens
47
+ if max_tokens <= budget:
48
+ max_tokens = budget + 4096
49
+ return budget, max_tokens
50
+
51
+
52
+ def _build_cached_system_param(system):
53
+ """Build Anthropic ``system`` as content blocks with a prompt-cache breakpoint.
54
+
55
+ Flow-efficiency D4-a: the system prompt (and the tool definitions that precede
56
+ it in the request) are stable across steps within a session, so marking the
57
+ LAST system block with ``cache_control: ephemeral`` lets Anthropic serve the
58
+ whole tools+system prefix from cache (~10x cheaper on repeated input).
59
+
60
+ Args:
61
+ system: the system prompt as a ``str`` or a list of content-block dicts.
62
+
63
+ Returns:
64
+ A list of content-block dicts (last one carrying ``cache_control`` when
65
+ caching is enabled), or ``None`` if ``system`` is falsy.
66
+
67
+ Caching is on by default; set ``ANTHROPIC_PROMPT_CACHE=0`` to disable.
68
+ Does not mutate the input list.
69
+ """
70
+ if not system:
71
+ return None
72
+
73
+ if isinstance(system, list):
74
+ blocks = [dict(b) for b in system] # shallow copy so we never mutate caller's list
75
+ else:
76
+ blocks = [{"type": "text", "text": system}]
77
+
78
+ from modules.llm.cache_hints import prompt_cache_enabled
79
+ if prompt_cache_enabled() and blocks:
80
+ blocks[-1] = {**blocks[-1], "cache_control": {"type": "ephemeral"}}
81
+ return blocks
82
+
83
+
84
+ def _apply_conversation_cache(messages, n: int = 3):
85
+ """Mark the last ``n`` conversation messages with ``cache_control: ephemeral``.
86
+
87
+ Flow-efficiency B1 (Reference ``system_and_3`` parity, see
88
+ docs/REFERENCE_VS_ROB_CONTEXT_SYSTEM_2026-06.md §9): Anthropic allows up to **4**
89
+ cache breakpoints per request. ``_build_cached_system_param`` already spends 1 on
90
+ the system block; this spends the remaining 3 on the tail of the *conversation*,
91
+ so the growing message prefix is served from cache instead of re-paying full input
92
+ cost every turn.
93
+
94
+ Does not mutate the caller's list. No-op (returns input unchanged) when
95
+ ``ANTHROPIC_PROMPT_CACHE`` is disabled or ``messages`` is empty.
96
+ """
97
+ from modules.llm.cache_hints import prompt_cache_enabled
98
+ if not prompt_cache_enabled() or not messages:
99
+ return messages
100
+
101
+ out = [dict(m) for m in messages]
102
+ for m in out[-n:]:
103
+ content = m.get("content")
104
+ if isinstance(content, str):
105
+ m["content"] = [{"type": "text", "text": content, "cache_control": {"type": "ephemeral"}}]
106
+ elif isinstance(content, list) and content:
107
+ # copy the last block so we don't mutate the shared dict, then mark it
108
+ content = [dict(b) if isinstance(b, dict) else b for b in content]
109
+ if isinstance(content[-1], dict):
110
+ content[-1] = {**content[-1], "cache_control": {"type": "ephemeral"}}
111
+ m["content"] = content
112
+ return out
113
+
114
+
115
+ class AnthropicClient(LLMClient):
116
+ """Anthropic Claude API client.
117
+
118
+ All model configuration comes from model_registry (single source of truth).
119
+ Deprecated fallback dicts removed Dec 13, 2025.
120
+ """
121
+
122
+ # UP-07: the dead EXTENDED_THINKING_MODELS dict was removed — its budgets now live in
123
+ # model_registry (thinking_budget_tokens) and drive a real `thinking` block below.
124
+
125
+ def __init__(self, config: BotConfig, name: str = "anthropic_client"):
126
+ """Initialize the client."""
127
+ super().__init__(config=config, name=name)
128
+ self._client = None
129
+
130
+ # Model and API configuration
131
+ self.model_type = config.get_llm_config()['anthropic'].get('model', get_default_model('anthropic'))
132
+ self.api_key = config.get_llm_config()['anthropic']['api_key']
133
+ self.last_response = None # Store the last response for token usage reporting
134
+
135
+ # Get defaults from model_registry (single source of truth)
136
+ from modules.llm.model_registry import get_model_config
137
+ model_config = get_model_config(self.model_type)
138
+
139
+ if model_config:
140
+ self.max_tokens = model_config.max_completion_tokens or 8192
141
+ else:
142
+ self.max_tokens = 8192 # Conservative fallback
143
+
144
+ # Resolve vision support via base helper (falls back to True if not in registry)
145
+ self.supports_vision = self._resolve_supports_vision()
146
+
147
+ self.temperature = 0.7 # Default temperature
148
+
149
+ self.logger.debug(
150
+ f"Anthropic client initialized: model={self.model_type}, "
151
+ f"supports_vision={self.supports_vision}"
152
+ )
153
+
154
+ def _validate_llm_config(self) -> None:
155
+ """Validate LLM config."""
156
+ if not self.api_key:
157
+ raise ServiceError("Anthropic API key not provided")
158
+
159
+ def _profile_base_url(self) -> Optional[str]:
160
+ """Read base_url from the Anthropic ProviderProfile (None => SDK default).
161
+
162
+ Delegates to the base ``_resolve_profile_base_url`` helper so that a
163
+ self-hosted gateway / proxy is configured in one place (profiles.py).
164
+ """
165
+ return self._resolve_profile_base_url("anthropic")
166
+
167
+ async def _setup_client(self) -> None:
168
+ """Set up the Anthropic client."""
169
+ try:
170
+ kwargs = {"api_key": self.api_key}
171
+ base_url = self._profile_base_url()
172
+ if base_url:
173
+ kwargs["base_url"] = base_url
174
+ self._client = anthropic.AsyncAnthropic(**kwargs)
175
+ self.logger.debug("Anthropic client setup completed")
176
+ except Exception as e:
177
+ raise ServiceError(f"Failed to set up Anthropic client: {e}")
178
+
179
+ async def _initialize(self) -> None:
180
+ """Initialize the client."""
181
+ if self._initialized:
182
+ return
183
+ try:
184
+ # Validate configuration
185
+ self._validate_llm_config()
186
+
187
+ # Initialize client with API key
188
+ await self._setup_client()
189
+
190
+ # Validate connection (skipped for fast startup; clients validate
191
+ # lazily on first real call — matches the base client and gemini)
192
+ if not self._skip_validate:
193
+ await self._validate_connection()
194
+
195
+ self._initialized = True
196
+
197
+ except Exception as e:
198
+ self.logger.error(f"Failed to initialize Anthropic client: {e}")
199
+ raise ServiceError(f"Failed to initialize Anthropic client: {e}")
200
+
201
+ async def _generate_with_tools(
202
+ self,
203
+ messages: List[Dict[str, str]],
204
+ tools: List[Dict[str, Any]],
205
+ system: Optional[str] = None,
206
+ temperature: Optional[float] = None,
207
+ max_tokens: Optional[int] = None,
208
+ **kwargs
209
+ ) -> Tuple[str, List[Dict[str, Any]]]:
210
+ """Generate response with native tool/function calling support.
211
+
212
+ Returns:
213
+ Tuple of (content, tool_calls) where tool_calls is a list of tool call dicts
214
+ """
215
+ start_time = time.time()
216
+ success = False
217
+ error_message = None
218
+
219
+ try:
220
+ # Ensure client is initialized
221
+ if not self._initialized:
222
+ await self._initialize()
223
+
224
+ # Convert messages to Anthropic format
225
+ anthropic_messages = []
226
+ for msg in messages:
227
+ role = msg.get('role', '')
228
+ content = msg.get('content', '')
229
+
230
+ # Skip system messages as they're handled separately, BUT recover
231
+ # the system prompt from the message list when no explicit `system`
232
+ # kwarg was supplied — the agent builds the real system prompt in the
233
+ # message list, not via the kwarg. Without this the entire system
234
+ # prompt (persona/brain-state format/security/tool guidance) is
235
+ # silently dropped on the Anthropic native tool path.
236
+ if role == 'system':
237
+ if system is None and isinstance(content, str) and content:
238
+ system = content
239
+ continue
240
+
241
+ # Map roles
242
+ if role == 'user':
243
+ anthropic_role = 'user'
244
+ elif role in ['assistant', 'ai']:
245
+ anthropic_role = 'assistant'
246
+ elif role == 'tool':
247
+ # Handle tool result messages
248
+ anthropic_role = 'user'
249
+ # Anthropic expects tool results in a specific format
250
+ tool_call_id = msg.get('tool_call_id', '')
251
+ content = [{
252
+ "type": "tool_result",
253
+ "tool_use_id": tool_call_id,
254
+ "content": content
255
+ }]
256
+ else:
257
+ self.logger.warning(f"Unknown role {role}, treating as user")
258
+ anthropic_role = 'user'
259
+
260
+ # Handle tool calls in assistant messages
261
+ if role == 'assistant' and 'tool_calls' in msg:
262
+ # Convert tool calls to Anthropic format
263
+ content_blocks = []
264
+ if content:
265
+ content_blocks.append({
266
+ "type": "text",
267
+ "text": content
268
+ })
269
+
270
+ for tool_call in msg['tool_calls']:
271
+ content_blocks.append({
272
+ "type": "tool_use",
273
+ "id": tool_call.get('id', ''),
274
+ "name": tool_call.get('function', {}).get('name', ''),
275
+ "input": json.loads(tool_call.get('function', {}).get('arguments', '{}'))
276
+ })
277
+
278
+ anthropic_messages.append({
279
+ "role": anthropic_role,
280
+ "content": content_blocks
281
+ })
282
+ else:
283
+ # Regular message
284
+ anthropic_messages.append({
285
+ "role": anthropic_role,
286
+ "content": content
287
+ })
288
+
289
+ # Use provided parameters or defaults
290
+ temp = temperature if temperature is not None else self.temperature
291
+
292
+ # Estimate input tokens (messages + system, Anthropic sends them separately)
293
+ estimated_input_tokens = count_messages_tokens(messages, self.model_type)
294
+ if system:
295
+ estimated_input_tokens += count_messages_tokens([{"role": "system", "content": system}], self.model_type)
296
+
297
+ # Clamp max_tokens to model limits (single canonical logic on base)
298
+ max_tokens_value = self._adjust_max_tokens(
299
+ messages=messages,
300
+ max_tokens=max_tokens,
301
+ estimated_input_tokens=estimated_input_tokens,
302
+ )
303
+
304
+ # Log request
305
+ self.logger.info(f"Anthropic API request with tools: model={self.model_type}, tools={len(tools)}, max_tokens={max_tokens_value}")
306
+
307
+ # Filter kwargs - CRITICAL: Exclude 'system' to prevent override
308
+ supported_params = {
309
+ 'model', 'messages', 'temperature', 'max_tokens',
310
+ 'tools', 'tool_choice', 'metadata', 'top_p', 'top_k', 'stop_sequences'
311
+ }
312
+ filtered_kwargs = {k: v for k, v in kwargs.items() if k in supported_params}
313
+
314
+ # Make API request with tools
315
+ # Convert system to list form + add prompt-cache breakpoint (D4-a).
316
+ system_param = _build_cached_system_param(system)
317
+
318
+ # Build API call params - only include system if not None
319
+ api_params = {
320
+ 'model': self.model_type,
321
+ 'messages': anthropic_messages,
322
+ 'temperature': temp,
323
+ 'max_tokens': max_tokens_value,
324
+ 'tools': tools,
325
+ 'tool_choice': kwargs.get('tool_choice', {'type': 'auto'}),
326
+ **filtered_kwargs
327
+ }
328
+ if system_param is not None:
329
+ api_params['system'] = system_param
330
+ # B1: cache the conversation prefix (system + last 3 msgs = 4 breakpoints).
331
+ api_params['messages'] = _apply_conversation_cache(api_params['messages'])
332
+
333
+ # UP-07: extended-thinking block from the registry budget (gated, default OFF).
334
+ # Anthropic requires max_tokens > budget_tokens and temperature == 1 when
335
+ # thinking is enabled. Per-call override via kwargs['thinking'] wins.
336
+ from modules.llm.model_registry import (
337
+ thinking_config_enabled, get_thinking_config, get_model_config,
338
+ )
339
+ # P1-9: extended thinking + tool calls requires replaying the assistant's
340
+ # thinking block(s) (with their signature) ahead of tool_use on the NEXT
341
+ # request; this client discards thinking blocks (see response processing
342
+ # below) and never replays them, so the follow-up tool_result request 400s
343
+ # at step 2 of a tool loop. Until block-replay lands, REFUSE to enable
344
+ # thinking when tools are present (the agent's primary path is a tool loop).
345
+ # A forced non-auto tool_choice is likewise invalid with thinking — moot
346
+ # here since we never combine them. One-time WARN so it's visible.
347
+ if 'thinking' not in api_params and thinking_config_enabled():
348
+ if tools:
349
+ if not getattr(self, '_thinking_tools_warned', False):
350
+ self.logger.warning(
351
+ "extended thinking is disabled for tool-calling requests in "
352
+ "this build (thinking blocks are not yet replayed, which would "
353
+ "400 the follow-up tool_result request). Set THINKING_CONFIG_"
354
+ "ENABLED=off to silence, or use thinking only on no-tool calls."
355
+ )
356
+ self._thinking_tools_warned = True
357
+ else:
358
+ tcfg = get_thinking_config(self.model_type)
359
+ budget = tcfg.get('budget_tokens')
360
+ if budget:
361
+ # H4: clamp so max_tokens > budget AND max_tokens <= the model cap
362
+ # (registry entries set budget == cap, which overran the cap -> 400).
363
+ _cfg = get_model_config(self.model_type)
364
+ model_cap = getattr(_cfg, 'max_completion_tokens', None) if _cfg else None
365
+ budget, max_tokens_value = _clamp_thinking(model_cap, budget, max_tokens_value)
366
+ if budget:
367
+ api_params['thinking'] = {'type': 'enabled', 'budget_tokens': budget}
368
+ api_params['temperature'] = 1 # required by the API when thinking is on
369
+ api_params['max_tokens'] = max_tokens_value
370
+
371
+ # FIXED: Use streaming for high max_tokens to avoid Anthropic SDK error
372
+ # "Streaming is required for operations that may take longer than 10 minutes"
373
+ # This happens when max_tokens is high (e.g., 65536). A thinking budget raises
374
+ # max_tokens above 8192, so this path is always taken when thinking is on.
375
+ use_streaming = max_tokens_value > 8192
376
+
377
+ response_text = ""
378
+ tool_calls = []
379
+
380
+ if use_streaming:
381
+ self.logger.debug(f"Using streaming for tool call (max_tokens={max_tokens_value})")
382
+ # Use streaming to avoid timeout error
383
+ async with self._client.messages.stream(**api_params) as stream:
384
+ self.last_response = await stream.get_final_message()
385
+ else:
386
+ self.last_response = await self._client.messages.create(**api_params)
387
+
388
+ success = True
389
+
390
+ # Process response - extract both content and tool calls
391
+ if hasattr(self.last_response, 'content') and self.last_response.content:
392
+ for block in self.last_response.content:
393
+ if hasattr(block, 'type'):
394
+ if block.type == 'text' and hasattr(block, 'text'):
395
+ response_text += block.text + " "
396
+ elif block.type == 'tool_use':
397
+ # Convert Anthropic tool use to standard format
398
+ tool_calls.append({
399
+ 'id': block.id,
400
+ 'type': 'function',
401
+ 'function': {
402
+ 'name': block.name,
403
+ 'arguments': json.dumps(block.input) if isinstance(block.input, dict) else str(block.input)
404
+ }
405
+ })
406
+
407
+ # Capture telemetry
408
+ self._extract_usage_and_capture_telemetry(start_time, success, None, kwargs.get('metadata'))
409
+
410
+ # Extract usage data
411
+ usage_data = self._extract_usage_data()
412
+
413
+ return response_text.strip(), tool_calls, usage_data
414
+
415
+ except Exception as e:
416
+ success = False
417
+ error_message = str(e)
418
+ self.logger.error(f"Anthropic tool calling error: {e}")
419
+
420
+ # Capture telemetry
421
+ self._extract_usage_and_capture_telemetry(start_time, success, error_message, kwargs.get('metadata'))
422
+
423
+ # Fall back to non-tool generation
424
+ self.logger.warning(f"Falling back to non-tool generation due to error: {e}")
425
+ response = await self._generate(messages, system, temperature, max_tokens, **kwargs)
426
+ # Canonical 3-tuple: usage is unavailable on this error path; use a zero/null dict
427
+ # consistent with _extract_usage_data()'s no-response shape.
428
+ fallback_usage: Dict[str, Optional[int]] = {
429
+ 'prompt_tokens': None,
430
+ 'completion_tokens': None,
431
+ 'total_tokens': None,
432
+ }
433
+ return response, [], fallback_usage
434
+
435
+ # ✅ REFERENCE IMPLEMENTATION FOR ALL PROVIDERS
436
+ # This method demonstrates the correct pattern:
437
+ # 1. Extract system/temperature/max_tokens from kwargs
438
+ # 2. Pass them explicitly to _generate_with_tools
439
+ # 3. _generate_with_tools uses them in API call
440
+ # OpenAI and Gemini should match this pattern.
441
+ async def generate_agent_response(
442
+ self,
443
+ messages: List[Dict[str, Any]],
444
+ tools: List[Dict[str, Any]],
445
+ **kwargs
446
+ ) -> Tuple[str, List[Dict[str, Any]], Dict[str, Optional[int]]]:
447
+ """Generate response with tool-calling support for agents.
448
+
449
+ This method bridges the adapter contract to enable native tool-calling
450
+ for Anthropic. It delegates to _generate_with_tools which handles the
451
+ wire-format conversion and API interaction.
452
+
453
+ Args:
454
+ messages: List of message dictionaries
455
+ tools: List of tool schemas in provider format
456
+ **kwargs: Additional generation parameters (including system, temperature, etc.)
457
+
458
+ Returns:
459
+ 3-tuple (content, tool_calls, usage_data). tool_calls may be empty list when
460
+ the model produced no tool calls. usage_data dict contains:
461
+ prompt_tokens, completion_tokens, total_tokens.
462
+
463
+ Raises:
464
+ LLMError: If generation fails
465
+ """
466
+ try:
467
+ self.logger.info(f"[generate_agent_response] Called with {len(messages)} messages and {len(tools) if tools else 0} tools")
468
+
469
+ # Extract system message if present in kwargs
470
+ system = kwargs.pop('system', None)
471
+ temperature = kwargs.pop('temperature', None)
472
+ max_tokens = kwargs.pop('max_tokens', None)
473
+
474
+ # Call the existing _generate_with_tools method
475
+ result = await self._generate_with_tools(
476
+ messages=messages,
477
+ tools=tools,
478
+ system=system,
479
+ temperature=temperature,
480
+ max_tokens=max_tokens,
481
+ **kwargs
482
+ )
483
+
484
+ # _generate_with_tools ALWAYS returns a 3-tuple (content, tool_calls, usage).
485
+ # Unpack directly; a non-3-tuple here is a programming error.
486
+ content, tool_calls, usage = result
487
+ self.logger.info(f"[generate_agent_response] Returning 3-tuple with {len(tool_calls)} tool calls + usage")
488
+
489
+ return result
490
+
491
+ except LLMError:
492
+ # Re-raise LLM errors as-is
493
+ raise
494
+ except Exception as e:
495
+ # Wrap other exceptions using core.exceptions pattern
496
+ self.logger.error(f"generate_agent_response failed: {str(e)}", exc_info=True)
497
+ raise LLMError(f"Failed to generate agent response: {str(e)}")
498
+
499
+ async def _generate(
500
+ self,
501
+ messages: List[Dict[str, str]],
502
+ system: Optional[str] = None,
503
+ temperature: Optional[float] = None,
504
+ max_tokens: Optional[int] = None,
505
+ **kwargs
506
+ ) -> str:
507
+ """Generate a response from Claude API."""
508
+ start_time = time.time()
509
+ success = False
510
+ error_message = None
511
+
512
+ try:
513
+ # Ensure client is initialized
514
+ if not self._initialized:
515
+ await self._initialize()
516
+
517
+ # Convert messages to Anthropic format, skipping system
518
+ anthropic_messages = []
519
+ for msg in messages:
520
+ role = msg.get('role', '')
521
+ content = msg.get('content', '')
522
+
523
+ # Skip system messages as they're handled separately in Claude API,
524
+ # BUT recover the in-list system prompt when no explicit `system`
525
+ # kwarg was supplied (see _generate_with_tools for rationale).
526
+ if role == 'system':
527
+ if system is None and isinstance(content, str) and content:
528
+ system = content
529
+ continue
530
+
531
+ # Map roles
532
+ if role == 'user':
533
+ anthropic_role = 'user'
534
+ elif role in ['assistant', 'ai']:
535
+ anthropic_role = 'assistant'
536
+ else:
537
+ self.logger.warning(f"Unknown role {role}, treating as user")
538
+ anthropic_role = 'user'
539
+
540
+ anthropic_messages.append({
541
+ "role": anthropic_role,
542
+ "content": content
543
+ })
544
+
545
+ # Use provided parameters or default to instance attributes
546
+ temp = temperature if temperature is not None else self.temperature
547
+
548
+ # Estimate input tokens (messages + system, Anthropic sends them separately)
549
+ estimated_input_tokens = count_messages_tokens(messages, self.model_type)
550
+ if system:
551
+ # Add system message token estimate
552
+ estimated_input_tokens += count_messages_tokens([{"role": "system", "content": system}], self.model_type)
553
+
554
+ # Clamp max_tokens to model limits (single canonical logic on base)
555
+ max_tokens_value = self._adjust_max_tokens(
556
+ messages=messages,
557
+ max_tokens=max_tokens,
558
+ estimated_input_tokens=estimated_input_tokens,
559
+ )
560
+
561
+ # Log request details with proper values being used
562
+ self.logger.info(f"Anthropic API request: model={self.model_type}, temperature={temp}, max_tokens={max_tokens_value}, est_input_tokens={estimated_input_tokens}")
563
+
564
+ # Filter kwargs to only include supported parameters
565
+ # CRITICAL: Exclude 'system' from kwargs to prevent override of system_param
566
+ supported_params = {
567
+ 'model', 'messages', 'temperature', 'max_tokens',
568
+ 'metadata', 'top_p', 'top_k', 'stop_sequences', 'stream'
569
+ }
570
+
571
+ filtered_kwargs = {k: v for k, v in kwargs.items() if k in supported_params}
572
+
573
+ # Make API request
574
+ # Convert system to list form + add prompt-cache breakpoint (D4-a).
575
+ system_param = _build_cached_system_param(system)
576
+
577
+ # Build API call params - only include system if not None
578
+ api_params = {
579
+ 'model': self.model_type,
580
+ 'messages': anthropic_messages,
581
+ 'temperature': temp,
582
+ 'max_tokens': max_tokens_value,
583
+ **filtered_kwargs
584
+ }
585
+ if system_param is not None:
586
+ api_params['system'] = system_param
587
+ # B1: cache the conversation prefix (system + last 3 msgs = 4 breakpoints).
588
+ api_params['messages'] = _apply_conversation_cache(api_params['messages'])
589
+
590
+ # FIXED: Use streaming for high max_tokens to avoid Anthropic SDK error
591
+ # "Streaming is required for operations that may take longer than 10 minutes"
592
+ use_streaming = max_tokens_value > 8192
593
+
594
+ if use_streaming:
595
+ self.logger.debug(f"Using streaming for _generate (max_tokens={max_tokens_value})")
596
+ async with self._client.messages.stream(**api_params) as stream:
597
+ self.last_response = await stream.get_final_message()
598
+ else:
599
+ self.last_response = await self._client.messages.create(**api_params)
600
+
601
+ # Mark as successful
602
+ success = True
603
+
604
+ # Process response
605
+ response_text = ""
606
+ if hasattr(self.last_response, 'content') and self.last_response.content:
607
+ text_blocks = [
608
+ block.text for block in self.last_response.content
609
+ if hasattr(block, 'text') and block.text
610
+ ]
611
+ response_text = " ".join(text_blocks)
612
+
613
+ # Capture telemetry with actual timing and usage data
614
+ self._extract_usage_and_capture_telemetry(start_time, success, None, kwargs.get('metadata'))
615
+
616
+ return response_text
617
+
618
+ except anthropic.APIError as e:
619
+ success = False
620
+ error_message = str(e)
621
+ self.logger.error(f"Anthropic API error: {e}")
622
+
623
+ # Capture telemetry for failed requests too
624
+ self._extract_usage_and_capture_telemetry(start_time, success, error_message, kwargs.get('metadata'))
625
+
626
+ raise ServiceError(f"Anthropic API error: {e}")
627
+ except Exception as e:
628
+ success = False
629
+ error_message = str(e)
630
+ self.logger.error(f"Error generating response from Anthropic: {e}")
631
+
632
+ # Capture telemetry for failed requests too
633
+ self._extract_usage_and_capture_telemetry(start_time, success, error_message, kwargs.get('metadata'))
634
+
635
+ raise ServiceError(f"Error generating response from Anthropic: {e}")
636
+
637
+ async def generate_response(
638
+ self,
639
+ prompt: Optional[Union[str, Dict[str, Any]]] = None,
640
+ messages: Optional[List[Dict[str, str]]] = None,
641
+ system: Optional[str] = None,
642
+ temperature: Optional[float] = None,
643
+ max_tokens: Optional[int] = None,
644
+ metadata: Optional[Dict[str, Any]] = None,
645
+ **kwargs
646
+ ) -> str:
647
+ """Generate a response from the LLM."""
648
+ try:
649
+ # Handle prompt formats
650
+ if messages is not None:
651
+ # Use messages directly if provided
652
+ formatted_messages = messages
653
+ elif isinstance(prompt, list) and all(isinstance(m, dict) for m in prompt):
654
+ # Prompt is already a list of messages
655
+ formatted_messages = prompt
656
+ elif isinstance(prompt, dict) and 'messages' in prompt:
657
+ # Extract messages and system from prompt dict
658
+ formatted_messages = prompt['messages']
659
+ if 'system' in prompt and not system:
660
+ system = prompt['system']
661
+ elif isinstance(prompt, str):
662
+ # Convert string prompt to message format
663
+ formatted_messages = [{"role": "user", "content": prompt}]
664
+ else:
665
+ # Default to empty message
666
+ formatted_messages = [{"role": "user", "content": "Hello"}]
667
+
668
+ # Anthropic doesn't support all metadata types
669
+ # Filter to what we can use
670
+ filtered_kwargs = kwargs.copy()
671
+
672
+ # Ensure metadata is passed through to _generate for telemetry
673
+ if metadata:
674
+ filtered_kwargs['metadata'] = metadata
675
+
676
+ # Extract Anthropic-supported metadata
677
+ anthropic_metadata = {}
678
+ for key, value in metadata.items():
679
+ # Anthropic supports user_id in metadata
680
+ if key == 'user_id' and isinstance(value, str):
681
+ anthropic_metadata[key] = value
682
+
683
+ # Only include if we have valid metadata for Anthropic
684
+ if anthropic_metadata:
685
+ filtered_kwargs.update(anthropic_metadata)
686
+
687
+ # Generate response
688
+ response = await self._generate(
689
+ messages=formatted_messages,
690
+ system=system,
691
+ temperature=temperature,
692
+ max_tokens=max_tokens,
693
+ **filtered_kwargs
694
+ )
695
+
696
+ return response
697
+
698
+ except Exception as e:
699
+ self.logger.error(f"Failed to generate response: {e}")
700
+ raise ServiceError(f"Failed to generate response: {e}")
701
+
702
+ async def _validate_connection(self) -> None:
703
+ """Validate connection to Anthropic."""
704
+ try:
705
+ # Simple test completion
706
+ response = await self._client.messages.create(
707
+ model=self.model_type,
708
+ max_tokens=10,
709
+ messages=[{"role": "user", "content": "Test connection"}]
710
+ )
711
+ if not response:
712
+ raise LLMConnectionError("No response from Anthropic API")
713
+ self.logger.debug("Anthropic API connection validated successfully")
714
+ except Exception as e:
715
+ self.logger.error(f"Failed to validate Anthropic connection: {e}")
716
+ raise ServiceError(f"Failed to validate Anthropic connection: {e}")
717
+
718
+ async def _cleanup_client(self) -> None:
719
+ """Clean up Anthropic client."""
720
+ try:
721
+ if hasattr(self, '_client'):
722
+ # Just set it to None for garbage collection
723
+ self._client = None
724
+ self.logger.debug("Anthropic client resources released")
725
+ except Exception as e:
726
+ self.logger.error(f"Error cleaning up Anthropic client: {e}")
727
+
728
+ async def cleanup(self) -> None:
729
+ """Clean up resources."""
730
+ await self._cleanup_client()
731
+ self._client = None
732
+ self._initialized = False
733
+ self.logger.info("Anthropic client cleaned up")
734
+
735
+ def _format_messages(self, prompt: Union[str, List[Dict[str, Any]], Dict[str, Any]]) -> List[Dict[str, Any]]:
736
+ """Format messages for Anthropic API."""
737
+ try:
738
+ if isinstance(prompt, str):
739
+ return [{
740
+ "role": "user",
741
+ "content": prompt
742
+ }]
743
+ elif isinstance(prompt, list):
744
+ return [
745
+ {
746
+ "role": msg.get("role", "user"),
747
+ "content": msg.get("content", "")
748
+ }
749
+ for msg in prompt
750
+ if msg.get("content") and msg.get("role") != "system" # Skip system and empty messages
751
+ ]
752
+ elif isinstance(prompt, dict):
753
+ messages = []
754
+
755
+ # Handle messages list
756
+ if "messages" in prompt:
757
+ return [
758
+ {
759
+ "role": msg.get("role", "user"),
760
+ "content": msg.get("content", "")
761
+ }
762
+ for msg in prompt["messages"]
763
+ if msg.get("content") and msg.get("role") != "system" # Skip system and empty messages
764
+ ]
765
+
766
+ return messages
767
+
768
+ return []
769
+
770
+ except Exception as e:
771
+ self.logger.error(f"Error formatting messages: {e}")
772
+ raise LLMError(f"Failed to format messages: {e}")
773
+
774
+ async def _make_validation_request(self) -> Any:
775
+ """Make minimal test request to Anthropic."""
776
+ return await self._client.messages.create(
777
+ model=self.model_type,
778
+ messages=[{"role": "user", "content": "test"}],
779
+ max_tokens=1
780
+ )
781
+
782
+ def _check_validation_response(self, response: Any) -> None:
783
+ """Validate Anthropic response."""
784
+ if not response or not response.content:
785
+ raise ValueError("Invalid response from Anthropic")
786
+
787
+ def _extract_usage_data(self) -> Dict[str, Optional[int]]:
788
+ """Extract usage data from last_response.
789
+
790
+ Returns dict with prompt_tokens, completion_tokens, total_tokens.
791
+ Returns None values if usage data not available.
792
+
793
+ Note: Anthropic uses input_tokens/output_tokens, we map to standard names.
794
+ """
795
+ if not self.last_response:
796
+ self.logger.warning("No last_response available for usage extraction")
797
+ return {'prompt_tokens': None, 'completion_tokens': None, 'total_tokens': None}
798
+
799
+ if not hasattr(self.last_response, 'usage') or not self.last_response.usage:
800
+ self.logger.warning(f"No usage data in response for model {self.model_type}")
801
+ return {'prompt_tokens': None, 'completion_tokens': None, 'total_tokens': None}
802
+
803
+ usage = self.last_response.usage
804
+ # Anthropic uses input_tokens/output_tokens instead of prompt/completion
805
+ input_tokens = getattr(usage, 'input_tokens', None)
806
+ output_tokens = getattr(usage, 'output_tokens', None)
807
+
808
+ # Anthropic reports cache reads/writes SEPARATELY and EXCLUDES them from
809
+ # input_tokens (total input = input_tokens + cache_read + cache_creation).
810
+ # Fold them back so the meter sees full input, expose cache READS as
811
+ # cached_tokens (billed at 0.1x) and cache CREATION as cache_creation_tokens
812
+ # (G3: billed at 1.25x via ModelPricing.cache_write_price downstream).
813
+ cache_read = getattr(usage, 'cache_read_input_tokens', 0) or 0
814
+ cache_creation = getattr(usage, 'cache_creation_input_tokens', 0) or 0
815
+ total_input = None if input_tokens is None else input_tokens + cache_read + cache_creation
816
+
817
+ # Calculate total
818
+ total_tokens = None
819
+ if total_input is not None and output_tokens is not None:
820
+ total_tokens = total_input + output_tokens
821
+
822
+ usage_data = {
823
+ 'prompt_tokens': total_input,
824
+ 'completion_tokens': output_tokens,
825
+ 'total_tokens': total_tokens,
826
+ 'cached_tokens': cache_read,
827
+ 'cache_creation_tokens': cache_creation
828
+ }
829
+
830
+ self.logger.debug(f"Extracted usage: {usage_data}")
831
+ return usage_data