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
tools/twitter_tool.py ADDED
@@ -0,0 +1,2086 @@
1
+ """Service that interacts with the Twitter API."""
2
+
3
+ import logging
4
+ import asyncio
5
+ import json
6
+ from typing import List, Optional, Dict, Any, Union, Callable
7
+ import tweepy # type: ignore
8
+ from core.config import BotConfig
9
+ import aiohttp
10
+ from utils.rate_limit_manager import RateLimitManager
11
+ import time
12
+ from datetime import datetime, timezone
13
+ from pydantic import BaseModel, ConfigDict, Field
14
+ import math
15
+ import traceback
16
+ from .base_tool import BaseTool, ToolStatus
17
+ from core.exceptions import APIError, ConfigurationError, AuthenticationError, RateLimitError, ResourceNotFoundError, ToolError, ServiceError
18
+ import os
19
+
20
+ # Import action models from centralized location
21
+ from tools.controller.views import (
22
+ TwitterSearchAction as TwitterSearchActionModel,
23
+ TwitterGetUserAction as TwitterGetUserActionModel,
24
+ TwitterGetTweetsAction as TwitterGetTweetsActionModel,
25
+ )
26
+
27
+
28
+ class DateTimeEncoder(json.JSONEncoder):
29
+ """Custom JSON encoder for datetime objects."""
30
+ def default(self, obj):
31
+ if isinstance(obj, datetime):
32
+ return obj.isoformat()
33
+ return super().default(obj)
34
+
35
+
36
+ # ---------------------------------------------------------------------------
37
+ # G1 — write-surface param models (Pydantic, extra="forbid").
38
+ # NOTE: this module deliberately has NO ``from __future__ import annotations`` —
39
+ # the Registry introspects action-closure first-param annotations; stringizing
40
+ # them breaks param-model routing. Keep concrete model classes; do not add it.
41
+ # ---------------------------------------------------------------------------
42
+ _TWEET_MAX = 280
43
+
44
+
45
+ # P6 (2026-07-02): 280 is the per-tweet WIRE limit, not the input cap. LLMs can't
46
+ # count characters, so a hard max_length=280 on the param model turned every long
47
+ # composition into a dead action (registry validation skipped the call; 'engage'
48
+ # goals completed having posted nothing). The tool now accepts longer text and
49
+ # auto-splits it into a chained thread; _TWEET_MAX_INPUT is a sanity cap only.
50
+ _TWEET_MAX_INPUT = 4000
51
+
52
+ _AUTOTHREAD_NOTE = (
53
+ " Text over 280 chars is automatically split at word boundaries and posted "
54
+ "as a numbered thread."
55
+ )
56
+
57
+
58
+ class TwitterPostAction(BaseModel):
59
+ model_config = ConfigDict(extra="forbid")
60
+ text: str = Field(..., min_length=1, max_length=_TWEET_MAX_INPUT,
61
+ description="Tweet text. ≤280 chars posts a single tweet." + _AUTOTHREAD_NOTE)
62
+ media_paths: Optional[List[str]] = Field(None, description="Local image/video file paths to upload + attach.")
63
+ poll_options: Optional[List[str]] = Field(None, description="2-4 poll choices (creates a poll).")
64
+ poll_duration_minutes: Optional[int] = Field(None, ge=5, le=10080, description="Poll duration in minutes.")
65
+
66
+
67
+ class TwitterReplyAction(BaseModel):
68
+ model_config = ConfigDict(extra="forbid")
69
+ tweet_id: str = Field(..., description="ID of the tweet to reply to.")
70
+ text: str = Field(..., min_length=1, max_length=_TWEET_MAX_INPUT,
71
+ description="Reply text. ≤280 chars posts a single reply." + _AUTOTHREAD_NOTE)
72
+ media_paths: Optional[List[str]] = Field(None, description="Local file paths to upload + attach.")
73
+
74
+
75
+ class TwitterQuoteAction(BaseModel):
76
+ model_config = ConfigDict(extra="forbid")
77
+ tweet_id: str = Field(..., description="ID of the tweet to quote.")
78
+ text: str = Field(..., min_length=1, max_length=_TWEET_MAX_INPUT,
79
+ description="Quote text. ≤280 chars posts a single quote-tweet." + _AUTOTHREAD_NOTE)
80
+
81
+
82
+ class TwitterThreadAction(BaseModel):
83
+ model_config = ConfigDict(extra="forbid")
84
+ texts: List[str] = Field(..., min_length=1, description="Ordered tweet texts; chained as a thread.")
85
+ media_paths: Optional[List[str]] = Field(None, description="Local file paths attached to the FIRST tweet.")
86
+
87
+
88
+ class TwitterDeleteAction(BaseModel):
89
+ model_config = ConfigDict(extra="forbid")
90
+ tweet_id: str = Field(..., description="ID of the tweet to delete.")
91
+
92
+
93
+ class TwitterTweetIdAction(BaseModel):
94
+ """Shared model for like/unlike/retweet/unretweet (a single tweet id)."""
95
+ model_config = ConfigDict(extra="forbid")
96
+ tweet_id: str = Field(..., description="Target tweet id.")
97
+
98
+
99
+ class TwitterUserAction(BaseModel):
100
+ """Shared model for follow/unfollow/mute/block (a username or numeric id)."""
101
+ model_config = ConfigDict(extra="forbid")
102
+ user: str = Field(..., description="Target username or numeric user id.")
103
+
104
+
105
+ class TwitterDMAction(BaseModel):
106
+ model_config = ConfigDict(extra="forbid")
107
+ recipient: str = Field(..., description="Recipient username or numeric user id.")
108
+ text: str = Field(..., min_length=1, max_length=10000, description="Direct-message text.")
109
+
110
+
111
+ class TwitterMentionsAction(BaseModel):
112
+ model_config = ConfigDict(extra="forbid")
113
+ max_results: int = Field(10, ge=5, le=100, description="Max mentions to fetch.")
114
+
115
+
116
+ class TwitterWhoamiAction(BaseModel):
117
+ model_config = ConfigDict(extra="forbid")
118
+
119
+
120
+ # Write actions gated behind TWITTER_ENABLED (reads + own-mentions/whoami stay on).
121
+ _TWITTER_WRITE_ACTIONS = frozenset({
122
+ "twitter_post", "twitter_reply", "twitter_quote", "twitter_thread",
123
+ "twitter_delete_tweet", "twitter_like", "twitter_unlike", "twitter_retweet",
124
+ "twitter_unretweet", "twitter_follow", "twitter_unfollow", "twitter_mute",
125
+ "twitter_block", "twitter_dm",
126
+ })
127
+
128
+ _FALSEY = {"0", "false", "no", "off", ""}
129
+
130
+
131
+ def twitter_write_enabled() -> bool:
132
+ """Gate for the Twitter WRITE surface (default OFF)."""
133
+ return os.getenv("TWITTER_ENABLED", "false").strip().lower() not in _FALSEY
134
+
135
+
136
+ class TwitterTool(BaseTool):
137
+ """Service that interacts with the Twitter API."""
138
+
139
+ @property
140
+ def required_services(self) -> Dict[str, str]:
141
+ """Get required services."""
142
+ return {
143
+ 'rate_limit_manager': 'Rate limit management',
144
+ }
145
+
146
+ @property
147
+ def optional_services(self) -> Dict[str, str]:
148
+ """Get optional services."""
149
+ return {
150
+ 'cache_manager': 'Cache management service',
151
+ # Optional: used only for persistence when a server container provides it.
152
+ # NOT required to post/read — keeping it optional lets the lightweight
153
+ # headless/CLI container load twitter (which has no database_manager).
154
+ 'database_manager': 'Database management',
155
+ }
156
+
157
+ def __init__(self, name: str, config: BotConfig, container: Optional[Any] = None):
158
+ """Initialize TwitterTool."""
159
+ super().__init__(name=name, config=config, container=container)
160
+
161
+ # Initialize API client
162
+ self.client = None
163
+ self.api_v1 = None # v1.1 tweepy.API for media upload (G1)
164
+ self._initialized = False
165
+ self._lazy_initialized = False
166
+ self._lazy_init_lock = asyncio.Lock()
167
+ # Per-class sliding-window rate-limit state (G1).
168
+ self._write_times: List[float] = []
169
+ self._dm_times: List[float] = []
170
+
171
+ # Get Twitter config
172
+ twitter_config = config.get_twitter_config()
173
+ self.api_key = twitter_config.get('api_key')
174
+ self.api_secret = twitter_config.get('api_secret')
175
+ self.access_token = twitter_config.get('access_token')
176
+ self.access_token_secret = twitter_config.get('access_token_secret')
177
+ self.bearer_token = twitter_config.get('bearer_token')
178
+
179
+ # Check credentials
180
+ missing_creds = []
181
+ for name, value in twitter_config.items():
182
+ if not value:
183
+ missing_creds.append(name.upper())
184
+
185
+ if missing_creds:
186
+ self.logger.warning(f"Missing Twitter credentials: {', '.join(missing_creds)}")
187
+ self._enabled = False
188
+ else:
189
+ self._enabled = True
190
+
191
+ async def initialize(self) -> None:
192
+ """Initialize the Twitter service using the BaseService implementation.
193
+
194
+ This ensures proper dependency injection and status tracking.
195
+ """
196
+ # Use the base class initialize which handles service dependencies
197
+ # and calls _initialize() internally
198
+ await super().initialize()
199
+
200
+ async def _initialize(self) -> None:
201
+ """Initialize Twitter service."""
202
+ try:
203
+ # Set a flag to indicate we're in initialization
204
+ self._initializing = True
205
+
206
+ # Initialize API client using the credentials from BotConfig
207
+ self.client = tweepy.Client(
208
+ bearer_token=self.bearer_token,
209
+ consumer_key=self.api_key,
210
+ consumer_secret=self.api_secret,
211
+ access_token=self.access_token,
212
+ access_token_secret=self.access_token_secret,
213
+ wait_on_rate_limit=False # We handle rate limiting ourselves
214
+ )
215
+ self._init_v1_client()
216
+
217
+ # Test connection
218
+ await self._test_api_connection()
219
+ # No need to set _status here as the BaseService initialize method will do it
220
+
221
+ except Exception as e:
222
+ self._status = ToolStatus.FAILED
223
+ self._error_message = str(e)
224
+ raise ToolError(f"Failed to initialize Twitter service: {e}")
225
+ finally:
226
+ # Clear the initialization flag
227
+ self._initializing = False
228
+
229
+ async def _test_api_connection(self) -> None:
230
+ """Test the connection to the Twitter API."""
231
+ try:
232
+ # Test connection by getting the authenticated user's profile
233
+ me = await self._make_request(
234
+ func=self.client.get_me,
235
+ endpoint_type='users' # Endpoint type for rate limiting
236
+ )
237
+
238
+ if me and hasattr(me, 'data'):
239
+ self.logger.info("Twitter client initialized successfully")
240
+ else:
241
+ self.logger.warning("Twitter API returned empty response during initialization")
242
+
243
+ except RateLimitError as e:
244
+ # Don't fail initialization due to rate limits
245
+ self.logger.warning(f"Twitter API rate limit hit during initialization: {e}")
246
+ # We'll consider this a successful init since the service can be used later
247
+
248
+ except Exception as e:
249
+ self.logger.warning(f"Twitter API test failed: {e}")
250
+ # Only raise if this isn't during initialization
251
+ if not getattr(self, '_initializing', False):
252
+ raise
253
+
254
+ async def _cleanup(self) -> None:
255
+ """Clean up Twitter service resources."""
256
+ try:
257
+ if self.client:
258
+ self.client = None
259
+ self.logger.info(f"{self.name} cleaned up successfully")
260
+ except Exception as e:
261
+ self.logger.error(f"Failed to cleanup {self.name}: {e}")
262
+ raise
263
+
264
+ async def _initialize_client(self) -> None:
265
+ """Initialize the Twitter API client."""
266
+ try:
267
+ import tweepy # type: ignore
268
+
269
+ # Initialize API client with credentials
270
+ self.client = tweepy.Client(
271
+ bearer_token=self.bearer_token,
272
+ consumer_key=self.api_key,
273
+ consumer_secret=self.api_secret,
274
+ access_token=self.access_token,
275
+ access_token_secret=self.access_token_secret,
276
+ wait_on_rate_limit=False # Changed to False to handle rate limits ourselves
277
+ )
278
+ self._init_v1_client()
279
+
280
+ # Test connection with rate limit handling
281
+ try:
282
+ me = await self._make_request(
283
+ func=self.client.get_me,
284
+ endpoint_type='users'
285
+ )
286
+
287
+ if me and hasattr(me, 'data'):
288
+ self.logger.info("Twitter client initialized successfully")
289
+ else:
290
+ self.logger.warning("Twitter API returned empty response during initialization")
291
+
292
+ except RateLimitError as e:
293
+ # Log warning but continue initialization
294
+ self.logger.warning(
295
+ f"Twitter API rate limit hit during initialization. Service will be enabled "
296
+ f"but some features may be temporarily unavailable: {str(e)}"
297
+ )
298
+ except Exception as e:
299
+ self.logger.warning(f"Twitter API test failed during initialization: {str(e)}")
300
+
301
+ # Enable service even if test fails
302
+ self._enabled = True
303
+
304
+ except Exception as e:
305
+ self.logger.error(f"Failed to initialize Twitter client: {e}")
306
+ self._enabled = False
307
+
308
+ async def _lazy_init(self) -> None:
309
+ """Lazily initialize the Twitter client when first needed."""
310
+ if self._lazy_initialized:
311
+ return
312
+
313
+ async with self._lazy_init_lock:
314
+ if self._lazy_initialized:
315
+ return
316
+
317
+ try:
318
+ # Test connection with rate limiting
319
+ me = await self._make_request(
320
+ func=self.client.get_me,
321
+ endpoint_type='users'
322
+ )
323
+
324
+ if not me or (hasattr(me, 'data') and not me.data):
325
+ raise ServiceError("Failed to get user data from Twitter API")
326
+
327
+ self._lazy_initialized = True
328
+ self.logger.info("Twitter client connection test successful")
329
+
330
+ except RateLimitError as e:
331
+ # Log warning but don't fail initialization
332
+ self.logger.warning(f"Rate limit encountered during Twitter connection test: {e}")
333
+ self._lazy_initialized = True
334
+ except Exception as e:
335
+ self.logger.error(f"Failed to test Twitter connection: {e}")
336
+ raise
337
+
338
+ async def _execute_request(self, func, *args, **kwargs):
339
+ """Execute the actual request.
340
+
341
+ This method directly executes the API call and handles possible rate limit errors.
342
+
343
+ Args:
344
+ func: The function to call
345
+ *args: Function arguments
346
+ **kwargs: Keyword arguments for the function
347
+ """
348
+ try:
349
+ # Ensure we have a callable function
350
+ if not callable(func):
351
+ raise ValueError(f"No callable function provided to _execute_request: func={func}, args={args}")
352
+
353
+ response = func(*args, **kwargs)
354
+
355
+ # Check remaining rate limit
356
+ if hasattr(response, 'response') and hasattr(response.response, 'headers'):
357
+ remaining = response.response.headers.get('x-rate-limit-remaining')
358
+ if remaining and int(remaining) < 10:
359
+ self.logger.warning(f"Twitter API rate limit low: {remaining} requests remaining")
360
+
361
+ return response
362
+
363
+ except tweepy.errors.TooManyRequests:
364
+ raise RateLimitError(
365
+ message="Twitter rate limit exceeded",
366
+ service="twitter"
367
+ )
368
+ except Exception as e:
369
+ self.logger.error(f"Error executing Twitter request: {e}")
370
+ raise
371
+
372
+ async def _make_request(self, func: callable, endpoint_type: str, *args, **kwargs) -> Any:
373
+ """Make a rate-limited request."""
374
+ if not self.client:
375
+ raise ConfigurationError("Twitter client not initialized")
376
+
377
+ try:
378
+ # Use the rate_limiter property from BaseService
379
+ if self.rate_limiter:
380
+ return await self.rate_limiter.execute_with_rate_limit(
381
+ service='twitter',
382
+ func=func, # Pass func directly as the function parameter
383
+ endpoint_type=endpoint_type,
384
+ *args, # Pass args directly
385
+ **kwargs # Pass kwargs directly
386
+ )
387
+ else:
388
+ # Fallback to direct execution if rate limiter is not available
389
+ self.logger.warning("Rate limiter not available, executing request directly")
390
+ return await self._execute_request(func, *args, **kwargs)
391
+ except RateLimitError:
392
+ if getattr(self.rate_limiter, '_initialization_mode', False):
393
+ self.logger.warning("Rate limit hit during initialization")
394
+ return None
395
+ raise
396
+ except Exception as e:
397
+ raise APIError(f"Twitter request failed: {str(e)}")
398
+
399
+ async def get_tweet(self, tweet_id: str) -> Optional[Dict]:
400
+ """Fetch a single tweet by ID.
401
+
402
+ Args:
403
+ tweet_id: The ID of the tweet to fetch
404
+
405
+ Returns:
406
+ Dictionary containing tweet data or None if not found
407
+
408
+ Raises:
409
+ tweepy.errors.TweepyException: For Twitter API errors
410
+ ValueError: For invalid tweet ID format
411
+ """
412
+ try:
413
+ if not tweet_id or not str(tweet_id).strip():
414
+ raise ValueError("Tweet ID cannot be empty")
415
+
416
+ if not self.client:
417
+ raise RuntimeError("Twitter client not initialized")
418
+
419
+ response = await self._make_request(
420
+ func=self.client.get_tweet,
421
+ endpoint_type='tweets',
422
+ id=tweet_id,
423
+ expansions=["author_id", "referenced_tweets.id"],
424
+ tweet_fields=["created_at", "text", "author_id", "conversation_id", "referenced_tweets", "public_metrics"],
425
+ user_fields=["username", "name", "description"]
426
+ )
427
+
428
+ if not response or not hasattr(response, 'data') or not response.data:
429
+ self.logger.warning(f"No tweet data found for ID: {tweet_id}")
430
+ return None
431
+
432
+ tweet_data = response.data
433
+
434
+ # Format tweet data
435
+ tweet = {
436
+ "id": tweet_id,
437
+ "text": tweet_data.text,
438
+ "author_id": tweet_data.author_id,
439
+ "created_at": tweet_data.created_at.isoformat() if hasattr(tweet_data, 'created_at') else None,
440
+ "conversation_id": getattr(tweet_data, 'conversation_id', None),
441
+ "public_metrics": getattr(tweet_data, 'public_metrics', {})
442
+ }
443
+
444
+ # Add referenced tweets if available
445
+ if hasattr(tweet_data, 'referenced_tweets') and tweet_data.referenced_tweets:
446
+ tweet["referenced_tweets"] = [
447
+ {"type": ref.type, "id": ref.id}
448
+ for ref in tweet_data.referenced_tweets
449
+ ]
450
+
451
+ # Add author info if available
452
+ if response.includes and "users" in response.includes:
453
+ author = next(
454
+ (u for u in response.includes["users"] if u.id == tweet_data.author_id),
455
+ None
456
+ )
457
+ if author:
458
+ tweet["author"] = {
459
+ "id": author.id,
460
+ "username": author.username,
461
+ "name": author.name,
462
+ "description": author.description
463
+ }
464
+
465
+ return tweet
466
+
467
+ except tweepy.errors.NotFound:
468
+ self.logger.warning(f"Tweet not found: {tweet_id}")
469
+ return None
470
+ except tweepy.errors.TweepyException as e:
471
+ self.logger.error(f"Twitter API error getting tweet {tweet_id}: {str(e)}")
472
+ raise
473
+ except Exception as e:
474
+ self.logger.error(f"Unexpected error getting tweet {tweet_id}: {str(e)}", exc_info=True)
475
+ raise
476
+
477
+ async def get_user_timeline(self, username_or_id: str, max_results: int = 10) -> Optional[List[Dict]]:
478
+ """Get a user's timeline tweets.
479
+
480
+ Args:
481
+ username_or_id: Username or user ID to get timeline for
482
+ max_results: Maximum number of tweets to return
483
+
484
+ Returns:
485
+ List of tweet dictionaries or None if error
486
+ """
487
+ try:
488
+ # First get user ID if username provided
489
+ if not str(username_or_id).isdigit():
490
+ user = await self.get_user_by_identifier(username_or_id)
491
+ if not user:
492
+ self.logger.error(f"Could not find user: {username_or_id}")
493
+ return None
494
+ user_id = user['id']
495
+ else:
496
+ user_id = username_or_id
497
+
498
+ response = await self._make_request(
499
+ func=self.client.get_users_tweets,
500
+ endpoint_type='tweets',
501
+ id=user_id, # Use resolved user_id
502
+ max_results=max_results,
503
+ tweet_fields=['created_at', 'text', 'public_metrics'],
504
+ expansions=['author_id']
505
+ )
506
+
507
+ if response and hasattr(response, 'data'):
508
+ return [
509
+ {
510
+ 'id': str(tweet.id),
511
+ 'text': tweet.text,
512
+ 'created_at': tweet.created_at.isoformat() if hasattr(tweet, 'created_at') else None,
513
+ 'metrics': getattr(tweet, 'public_metrics', {})
514
+ }
515
+ for tweet in response.data
516
+ ]
517
+ return None
518
+
519
+ except Exception as e:
520
+ self.logger.error(f"Error getting user timeline: {str(e)}", exc_info=True)
521
+ return None
522
+
523
+ async def get_conversation_thread(self, conversation_id: str, max_results: int = 10) -> Optional[Dict]:
524
+ """Get tweets in a conversation thread.
525
+
526
+ Args:
527
+ conversation_id: ID of the conversation to fetch
528
+ max_results: Maximum number of tweets to fetch (default: 10)
529
+
530
+ Returns:
531
+ Dict containing thread data or None if not found
532
+ """
533
+ try:
534
+ # Ensure max_results is within valid range
535
+ max_results = max(10, min(100, max_results))
536
+
537
+ # Get initial tweet using _make_request wrapper
538
+ initial_tweet = await self._make_request(
539
+ func=self.client.get_tweet,
540
+ endpoint_type='tweets',
541
+ id=conversation_id,
542
+ tweet_fields=['author_id', 'conversation_id', 'created_at', 'text', 'referenced_tweets'],
543
+ expansions=['author_id', 'referenced_tweets.id', 'referenced_tweets.id.author_id'],
544
+ user_fields=['id', 'name', 'username', 'description']
545
+ )
546
+
547
+ if not initial_tweet or not hasattr(initial_tweet, 'data'):
548
+ self.logger.warning(f"Conversation {conversation_id} not found")
549
+ return None
550
+
551
+ # Get conversation tweets with expansions
552
+ conversation_tweets = await self._make_request(
553
+ func=self.client.search_recent_tweets,
554
+ endpoint_type='search',
555
+ query=f"conversation_id:{conversation_id}",
556
+ max_results=max_results,
557
+ tweet_fields=['author_id', 'conversation_id', 'created_at', 'text', 'referenced_tweets'],
558
+ expansions=['author_id', 'referenced_tweets.id', 'referenced_tweets.id.author_id'],
559
+ user_fields=['id', 'name', 'username', 'description']
560
+ )
561
+
562
+ # Initialize thread data structure
563
+ thread_data = {
564
+ 'data': [],
565
+ 'includes': {'users': [], 'tweets': []},
566
+ 'user_map': {} # New: mapping of user_id to user data
567
+ }
568
+
569
+ # Build user map from initial tweet
570
+ if hasattr(initial_tweet, 'includes') and 'users' in initial_tweet.includes:
571
+ for user in initial_tweet.includes['users']:
572
+ user_dict = {
573
+ 'id': str(user.id),
574
+ 'username': user.username,
575
+ 'name': user.name,
576
+ 'description': getattr(user, 'description', None)
577
+ }
578
+ thread_data['user_map'][str(user.id)] = user_dict
579
+ thread_data['includes']['users'].append(user_dict)
580
+
581
+ # Add initial tweet data with username
582
+ if hasattr(initial_tweet, 'data'):
583
+ author_id = str(initial_tweet.data.author_id)
584
+ tweet_dict = {
585
+ 'id': str(initial_tweet.data.id),
586
+ 'text': initial_tweet.data.text,
587
+ 'author_id': author_id,
588
+ 'username': thread_data['user_map'].get(author_id, {}).get('username'),
589
+ 'created_at': initial_tweet.data.created_at.isoformat() if hasattr(initial_tweet.data, 'created_at') else None,
590
+ 'conversation_id': initial_tweet.data.conversation_id,
591
+ 'referenced_tweets': [
592
+ {'type': ref.type, 'id': ref.id}
593
+ for ref in initial_tweet.data.referenced_tweets
594
+ ] if hasattr(initial_tweet.data, 'referenced_tweets') else []
595
+ }
596
+ thread_data['data'].append(tweet_dict)
597
+
598
+ # Process conversation tweets
599
+ if conversation_tweets and hasattr(conversation_tweets, 'data'):
600
+ # Update user map with any new users
601
+ if hasattr(conversation_tweets, 'includes') and 'users' in conversation_tweets.includes:
602
+ for user in conversation_tweets.includes['users']:
603
+ if str(user.id) not in thread_data['user_map']:
604
+ user_dict = {
605
+ 'id': str(user.id),
606
+ 'username': user.username,
607
+ 'name': user.name,
608
+ 'description': getattr(user, 'description', None)
609
+ }
610
+ thread_data['user_map'][str(user.id)] = user_dict
611
+ thread_data['includes']['users'].append(user_dict)
612
+
613
+ # Add conversation tweets with usernames
614
+ existing_ids = {t['id'] for t in thread_data['data']}
615
+ for tweet in conversation_tweets.data:
616
+ if str(tweet.id) not in existing_ids:
617
+ author_id = str(tweet.author_id)
618
+ tweet_dict = {
619
+ 'id': str(tweet.id),
620
+ 'text': tweet.text,
621
+ 'author_id': author_id,
622
+ 'username': thread_data['user_map'].get(author_id, {}).get('username'),
623
+ 'created_at': tweet.created_at.isoformat() if hasattr(tweet, 'created_at') else None,
624
+ 'conversation_id': tweet.conversation_id,
625
+ 'referenced_tweets': [
626
+ {'type': ref.type, 'id': ref.id}
627
+ for ref in tweet.referenced_tweets
628
+ ] if hasattr(tweet, 'referenced_tweets') else []
629
+ }
630
+ thread_data['data'].append(tweet_dict)
631
+
632
+ # Sort tweets by creation time
633
+ thread_data['data'].sort(
634
+ key=lambda x: x.get('created_at', ''),
635
+ reverse=False # Oldest first
636
+ )
637
+
638
+ self.logger.debug(
639
+ f"[THREAD] Found {len(thread_data['data'])} tweets and {len(thread_data['user_map'])} users "
640
+ f"in conversation {conversation_id}"
641
+ )
642
+ return thread_data
643
+
644
+ except Exception as e:
645
+ self.logger.error(f"Error fetching conversation thread: {str(e)}", exc_info=True)
646
+ return None
647
+
648
+ async def get_user_by_identifier(self, identifier: str) -> Optional[Dict]:
649
+ """Get user data by username or ID.
650
+
651
+ Args:
652
+ identifier: Username or user ID
653
+
654
+ Returns:
655
+ Dictionary containing user data or None if not found
656
+ """
657
+ try:
658
+ if not identifier:
659
+ raise ValueError("User identifier cannot be empty")
660
+
661
+ if not self.client:
662
+ raise RuntimeError("Twitter client not initialized")
663
+
664
+ # Convert identifier to string if it's an integer
665
+ str_identifier = str(identifier)
666
+
667
+ response = await self._make_request(
668
+ func=self.client.get_user,
669
+ endpoint_type='users', # Specify endpoint type for rate limiting
670
+ id=str_identifier if str_identifier.isdigit() else None,
671
+ username=str_identifier if not str_identifier.isdigit() else None,
672
+ user_fields=["description", "created_at", "public_metrics", "protected", "verified"]
673
+ )
674
+
675
+ if not response or not hasattr(response, 'data') or not response.data:
676
+ self.logger.warning(f"No user data found for identifier: {identifier}")
677
+ return None
678
+
679
+ user_data = response.data
680
+
681
+ # Format user data
682
+ user = {
683
+ "id": user_data.id,
684
+ "username": user_data.username,
685
+ "name": user_data.name,
686
+ "description": user_data.description,
687
+ "created_at": user_data.created_at.isoformat() if hasattr(user_data, 'created_at') else None,
688
+ "public_metrics": getattr(user_data, 'public_metrics', {}),
689
+ "protected": getattr(user_data, 'protected', False),
690
+ "verified": getattr(user_data, 'verified', False)
691
+ }
692
+
693
+ return user
694
+
695
+ except tweepy.errors.NotFound:
696
+ self.logger.warning(f"User not found: {identifier}")
697
+ return None
698
+ except tweepy.errors.TweepyException as e:
699
+ self.logger.error(f"Twitter API error getting user {identifier}: {str(e)}")
700
+ raise
701
+ except Exception as e:
702
+ self.logger.error(f"Unexpected error getting user data: {str(e)}", exc_info=True)
703
+ raise
704
+
705
+ async def get_user_profile_async(self, username: str) -> Optional[Dict]:
706
+ """Get a user's profile data asynchronously.
707
+
708
+ Args:
709
+ username: Twitter username
710
+
711
+ Returns:
712
+ Dictionary containing user profile data or None if not found
713
+ """
714
+ return await self.get_user_by_identifier(username)
715
+
716
+ async def get_engagement_profiles(self, username: Optional[str] = None) -> List[Dict]:
717
+ """Get profiles for engagement based on configured criteria.
718
+
719
+ Args:
720
+ username: Optional username to get specific profile
721
+
722
+ Returns:
723
+ List of engagement profile dictionaries
724
+
725
+ Raises:
726
+ tweepy.errors.TweepyException: For Twitter API errors
727
+ """
728
+ try:
729
+ self.logger.debug(f"Getting engagement profiles for username: {username}")
730
+ profiles = []
731
+
732
+ if username:
733
+ # Get user profile data
734
+ self.logger.debug(f"Fetching user profile for: {username}")
735
+ user = await self.get_user_profile_async(username)
736
+
737
+ if user:
738
+ # Get recent tweets for engagement analysis
739
+ tweets = await self.get_user_timeline(user['id'], max_results=10) or []
740
+
741
+ # Extract metrics from user data
742
+ metrics = user.get('public_metrics', {})
743
+
744
+ profile = {
745
+ 'id': user['id'],
746
+ 'username': user['username'],
747
+ 'name': user['name'],
748
+ 'description': user['description'],
749
+ 'followers_count': metrics.get('followers_count', 0),
750
+ 'following_count': metrics.get('following_count', 0),
751
+ 'tweet_count': metrics.get('tweet_count', 0),
752
+ 'engagement_score': self._calculate_engagement_score(user, tweets),
753
+ 'recent_tweets': tweets
754
+ }
755
+ self.logger.debug(f"Created profile for {username}")
756
+ profiles.append(profile)
757
+ else:
758
+ self.logger.warning(f"No user profile found for username: {username}")
759
+
760
+ return profiles
761
+
762
+ except tweepy.errors.TweepyException as e:
763
+ self.logger.error(f"Twitter API error getting engagement profiles: {str(e)}")
764
+ raise
765
+ except Exception as e:
766
+ self.logger.error(f"Unexpected error getting engagement profiles: {str(e)}", exc_info=True)
767
+ # Return empty list on error instead of raising
768
+ return []
769
+
770
+ def _calculate_engagement_score(self, user: Dict, tweets: Optional[List[Dict]] = None) -> float:
771
+ """Calculate engagement score based on user metrics and recent tweets.
772
+
773
+ Args:
774
+ user: User profile data
775
+ tweets: Optional list of recent tweets
776
+
777
+ Returns:
778
+ float: Engagement score between 0 and 1
779
+ """
780
+ try:
781
+ score = 0.0
782
+ weights = {
783
+ 'followers': 0.3,
784
+ 'tweets': 0.2,
785
+ 'recent_activity': 0.5
786
+ }
787
+
788
+ # Base score from follower count (log scale to handle large numbers)
789
+ followers = user.get('followers_count', 0)
790
+ if followers > 0:
791
+ score += weights['followers'] * min(1.0, (1 + math.log10(followers)) / 7.0)
792
+
793
+ # Activity score from tweet count
794
+ tweet_count = user.get('tweet_count', 0)
795
+ if tweet_count > 0:
796
+ score += weights['tweets'] * min(1.0, (1 + math.log10(tweet_count)) / 5.0)
797
+
798
+ # Recent activity score from provided tweets
799
+ if tweets:
800
+ recent_score = 0.0
801
+ for tweet in tweets:
802
+ metrics = tweet.get('public_metrics', {})
803
+ likes = metrics.get('like_count', 0)
804
+ retweets = metrics.get('retweet_count', 0)
805
+ replies = metrics.get('reply_count', 0)
806
+
807
+ # Calculate engagement rate for this tweet
808
+ engagement = likes + (retweets * 2) + (replies * 3) # Weight replies higher
809
+ if followers > 0:
810
+ engagement_rate = min(1.0, engagement / followers)
811
+ recent_score += engagement_rate
812
+
813
+ # Average the recent tweet scores
814
+ if len(tweets) > 0:
815
+ recent_score /= len(tweets)
816
+ score += weights['recent_activity'] * recent_score
817
+
818
+ return min(1.0, max(0.0, score))
819
+
820
+ except Exception as e:
821
+ self.logger.error(f"Error calculating engagement score: {str(e)}")
822
+ return 0.5 # Return middle score on error
823
+
824
+ async def get_authenticated_user_id(self) -> Optional[str]:
825
+ """Get the authenticated user's ID.
826
+
827
+ Returns:
828
+ String containing the user ID or None if failed
829
+ """
830
+ try:
831
+ user_profile = await self.get_user_profile()
832
+ if user_profile and user_profile.get('data', {}).get('id'):
833
+ return user_profile['data']['id']
834
+ return None
835
+
836
+ except Exception as e:
837
+ self.logger.error(f"Error getting authenticated user ID: {str(e)}", exc_info=True)
838
+ return None
839
+
840
+ async def create_tweet(self, text: str, media_ids: Optional[List[str]] = None) -> Optional[Dict]:
841
+ """Alias for post() method to maintain compatibility.
842
+
843
+ Args:
844
+ text: Tweet text content
845
+ media_ids: Optional list of media IDs to attach
846
+
847
+ Returns:
848
+ Dictionary containing the created tweet data or None if failed
849
+ """
850
+ return await self.post(text=text, media_ids=media_ids)
851
+
852
+ async def like(self, tweet_id: str) -> bool:
853
+ """Like a tweet.
854
+
855
+ Args:
856
+ tweet_id: ID of the tweet to like
857
+
858
+ Returns:
859
+ bool: True if successful, False otherwise
860
+
861
+ Raises:
862
+ ValueError: If tweet_id is invalid
863
+ tweepy.errors.TweepyException: For Twitter API errors
864
+ """
865
+ try:
866
+ response = await self._make_request(
867
+ func=self.client.like,
868
+ endpoint_type='likes',
869
+ tweet_id=tweet_id
870
+ )
871
+ return bool(response and response.data and response.data.get('liked'))
872
+ except Exception as e:
873
+ self.logger.error(f"Error liking tweet {tweet_id}: {str(e)}")
874
+ return False
875
+
876
+ async def unlike(self, tweet_id: str) -> bool:
877
+ """Unlike a tweet.
878
+
879
+ Args:
880
+ tweet_id: ID of the tweet to unlike
881
+
882
+ Returns:
883
+ bool: True if successful, False otherwise
884
+
885
+ Raises:
886
+ ValueError: If tweet_id is invalid
887
+ tweepy.errors.TweepyException: For Twitter API errors
888
+ """
889
+ try:
890
+ if not tweet_id or not str(tweet_id).strip():
891
+ raise ValueError("Tweet ID cannot be empty")
892
+
893
+ if not self.client:
894
+ raise RuntimeError("Twitter client not initialized")
895
+
896
+ response = await self._make_request(
897
+ func=self.client.unlike,
898
+ tweet_id=tweet_id
899
+ )
900
+
901
+ if response and hasattr(response, 'data') and response.data:
902
+ self.logger.info(f"Successfully unliked tweet {tweet_id}")
903
+ return True
904
+
905
+ self.logger.warning(f"Failed to unlike tweet {tweet_id}")
906
+ return False
907
+
908
+ except tweepy.errors.Forbidden as e:
909
+ self.logger.warning(f"Not allowed to unlike tweet {tweet_id}: {str(e)}")
910
+ return False
911
+ except tweepy.errors.NotFound:
912
+ self.logger.warning(f"Tweet not found: {tweet_id}")
913
+ return False
914
+ except tweepy.errors.TweepyException as e:
915
+ self.logger.error(f"Twitter API error unliking tweet: {str(e)}")
916
+ raise
917
+ except ValueError as e:
918
+ self.logger.error(str(e))
919
+ raise
920
+ except Exception as e:
921
+ self.logger.error(f"Unexpected error unliking tweet: {str(e)}", exc_info=True)
922
+ raise
923
+
924
+ async def retweet(self, tweet_id: str) -> bool:
925
+ """Retweet a tweet.
926
+
927
+ Args:
928
+ tweet_id: ID of the tweet to retweet
929
+
930
+ Returns:
931
+ bool: True if successful, False otherwise
932
+
933
+ Raises:
934
+ ValueError: If tweet_id is invalid
935
+ tweepy.errors.TweepyException: For Twitter API errors
936
+ """
937
+ try:
938
+ response = await self._make_request(
939
+ func=self.client.retweet,
940
+ endpoint_type='retweets',
941
+ tweet_id=tweet_id
942
+ )
943
+ return bool(response and response.data and response.data.get('retweeted'))
944
+ except Exception as e:
945
+ self.logger.error(f"Error retweeting tweet {tweet_id}: {str(e)}")
946
+ return False
947
+
948
+ async def unretweet(self, tweet_id: str) -> bool:
949
+ """Remove a retweet.
950
+
951
+ Args:
952
+ tweet_id: ID of the tweet to unretweet
953
+
954
+ Returns:
955
+ bool: True if successful, False otherwise
956
+
957
+ Raises:
958
+ ValueError: If tweet_id is invalid
959
+ tweepy.errors.TweepyException: For Twitter API errors
960
+ """
961
+ try:
962
+ if not tweet_id or not str(tweet_id).strip():
963
+ raise ValueError("Tweet ID cannot be empty")
964
+
965
+ if not self.client:
966
+ raise RuntimeError("Twitter client not initialized")
967
+
968
+ response = await self._make_request(
969
+ func=self.client.unretweet,
970
+ tweet_id=tweet_id
971
+ )
972
+
973
+ if response and hasattr(response, 'data') and response.data:
974
+ self.logger.info(f"Successfully unretweeted tweet {tweet_id}")
975
+ return True
976
+
977
+ self.logger.warning(f"Failed to unretweet tweet {tweet_id}")
978
+ return False
979
+
980
+ except tweepy.errors.Forbidden as e:
981
+ self.logger.warning(f"Not allowed to unretweet tweet {tweet_id}: {str(e)}")
982
+ return False
983
+ except tweepy.errors.NotFound:
984
+ self.logger.warning(f"Tweet not found: {tweet_id}")
985
+ return False
986
+ except tweepy.errors.TweepyException as e:
987
+ self.logger.error(f"Twitter API error unretweeting tweet: {str(e)}")
988
+ raise
989
+ except ValueError as e:
990
+ self.logger.error(str(e))
991
+ raise
992
+ except Exception as e:
993
+ self.logger.error(f"Unexpected error unretweeting tweet: {str(e)}", exc_info=True)
994
+ raise
995
+
996
+ async def reply(self, tweet_id: str, text: str) -> Optional[Dict]:
997
+ """Reply to a tweet.
998
+
999
+ Args:
1000
+ tweet_id: ID of the tweet to reply to
1001
+ text: Reply text content
1002
+
1003
+ Returns:
1004
+ Dict: Created tweet data or None if failed
1005
+
1006
+ Raises:
1007
+ ValueError: If tweet_id or text is invalid
1008
+ tweepy.errors.TweepyException: For Twitter API errors
1009
+ """
1010
+ try:
1011
+ response = await self._make_request(
1012
+ func=self.client.create_tweet,
1013
+ endpoint_type='replies',
1014
+ text=text,
1015
+ in_reply_to_tweet_id=tweet_id
1016
+ )
1017
+
1018
+ if response and hasattr(response, 'data'):
1019
+ return {
1020
+ 'id': response.data['id'],
1021
+ 'text': response.data['text']
1022
+ }
1023
+ return None
1024
+ except Exception as e:
1025
+ self.logger.error(f"Error replying to tweet {tweet_id}: {str(e)}")
1026
+ return None
1027
+
1028
+ async def quote_tweet(self, tweet_id: str, text: str) -> Optional[Dict]:
1029
+ """Quote a tweet.
1030
+
1031
+ Args:
1032
+ tweet_id: ID of tweet to quote
1033
+ text: Text content for the quote tweet
1034
+
1035
+ Returns:
1036
+ Dict containing the created tweet data or None if failed
1037
+ """
1038
+ try:
1039
+ # Verify tweet exists first
1040
+ tweet = await self.get_tweet(tweet_id)
1041
+ if not tweet:
1042
+ self.logger.warning(f"Could not find tweet {tweet_id} to quote")
1043
+ return None
1044
+
1045
+ # Create quote tweet
1046
+ response = await self._make_request(
1047
+ func=self.client.create_tweet,
1048
+ endpoint_type='tweets', # Add endpoint type
1049
+ text=text,
1050
+ quote_tweet_id=tweet_id
1051
+ )
1052
+
1053
+ if response and hasattr(response, 'data'):
1054
+ tweet_data = response.data
1055
+ self.logger.info(f"Successfully quoted tweet {tweet_id}")
1056
+ return {
1057
+ 'data': {
1058
+ 'id': str(tweet_data.id),
1059
+ 'text': tweet_data.text,
1060
+ 'created_at': tweet_data.created_at.isoformat() if hasattr(tweet_data, 'created_at') else None,
1061
+ 'conversation_id': getattr(tweet_data, 'conversation_id', None),
1062
+ 'quoted_tweet_id': tweet_id
1063
+ }
1064
+ }
1065
+
1066
+ self.logger.warning(f"Failed to quote tweet {tweet_id}")
1067
+ return None
1068
+
1069
+ except Exception as e:
1070
+ self.logger.error(f"Unexpected error quoting tweet: {str(e)}", exc_info=True)
1071
+ return None
1072
+
1073
+ async def get_tweets_batch(self, tweet_ids: List[str]) -> Dict[str, Dict]:
1074
+ """Get multiple tweets by their IDs.
1075
+
1076
+ Args:
1077
+ tweet_ids: List of tweet IDs to fetch
1078
+
1079
+ Returns:
1080
+ Dict mapping tweet IDs to tweet data
1081
+ """
1082
+ try:
1083
+ self.logger.debug(f"Processing batch of {len(tweet_ids)} tweets")
1084
+
1085
+ response = await self._make_request(
1086
+ func=self.client.get_tweets,
1087
+ endpoint_type='tweets', # Add endpoint_type parameter
1088
+ ids=tweet_ids,
1089
+ tweet_fields=['created_at', 'text', 'referenced_tweets', 'public_metrics']
1090
+ )
1091
+
1092
+ if not response or not response.data:
1093
+ return {}
1094
+
1095
+ # Convert list of tweets to dict keyed by ID
1096
+ return {str(tweet.id): tweet.data for tweet in response.data}
1097
+
1098
+ except Exception as e:
1099
+ self.logger.error(f"Unexpected error fetching tweets batch: {str(e)}")
1100
+ if hasattr(e, '__traceback__'):
1101
+ self.logger.error(traceback.format_exc())
1102
+ return {}
1103
+
1104
+ def _filter_new_tweets(self, conversation_id: str, tweets: List[Dict]) -> List[Dict]:
1105
+ """Filter out already processed tweets.
1106
+
1107
+ Args:
1108
+ conversation_id: ID of the conversation
1109
+ tweets: List of tweets to filter
1110
+
1111
+ Returns:
1112
+ List of unprocessed tweets
1113
+
1114
+ Raises:
1115
+ ValueError: If conversation_id is invalid or tweets is invalid
1116
+ """
1117
+ try:
1118
+ if not conversation_id or not str(conversation_id).strip():
1119
+ raise ValueError("Conversation ID cannot be empty")
1120
+
1121
+ if not isinstance(tweets, list):
1122
+ raise ValueError(f"tweets must be a list, got {type(tweets)}")
1123
+
1124
+ if not hasattr(self, 'active_conversations'):
1125
+ self.logger.warning("No active conversations found")
1126
+ return []
1127
+
1128
+ if conversation_id not in self.active_conversations:
1129
+ self.logger.warning(f"Conversation {conversation_id} not found in active conversations")
1130
+ return []
1131
+
1132
+ processed_tweets = self.active_conversations[conversation_id].get('processed_tweets', set())
1133
+ new_tweets = []
1134
+
1135
+ for tweet in tweets:
1136
+ if not isinstance(tweet, dict):
1137
+ self.logger.warning(f"Invalid tweet format: {type(tweet)}")
1138
+ continue
1139
+
1140
+ tweet_id = tweet.get('id')
1141
+ if not tweet_id:
1142
+ self.logger.warning("Tweet missing ID")
1143
+ continue
1144
+
1145
+ if tweet_id not in processed_tweets:
1146
+ # Check if it's a reply to a tweet we've processed
1147
+ referenced_tweets = tweet.get('referenced_tweets', [])
1148
+ is_reply = any(
1149
+ ref.get('type') == 'replied_to'
1150
+ for ref in referenced_tweets
1151
+ if isinstance(ref, dict)
1152
+ )
1153
+
1154
+ if is_reply:
1155
+ # Add replies to new tweets even if the parent is processed
1156
+ new_tweets.append(tweet)
1157
+ else:
1158
+ # For non-replies, add if not processed
1159
+ new_tweets.append(tweet)
1160
+
1161
+ self.logger.debug(
1162
+ f"Found {len(new_tweets)} new tweets out of {len(tweets)} total tweets in conversation {conversation_id}"
1163
+ )
1164
+ return new_tweets
1165
+
1166
+ except Exception as e:
1167
+ self.logger.error(f"Error filtering tweets: {str(e)}", exc_info=True)
1168
+ return []
1169
+
1170
+ async def post(self, text: str, media_ids: Optional[List[str]] = None) -> Optional[Dict]:
1171
+ """Post a new tweet.
1172
+
1173
+ Args:
1174
+ text: Tweet text content
1175
+ media_ids: Optional list of media IDs to attach
1176
+
1177
+ Returns:
1178
+ Dictionary containing the created tweet data or None if failed
1179
+ """
1180
+ try:
1181
+ # Build kwargs for create_tweet
1182
+ kwargs = {'text': text}
1183
+ if media_ids and len(media_ids) > 0:
1184
+ kwargs['media_ids'] = media_ids
1185
+
1186
+ response = await self._make_request(
1187
+ func=self.client.create_tweet,
1188
+ endpoint_type='tweets',
1189
+ **kwargs
1190
+ )
1191
+
1192
+ if response and hasattr(response, 'data'):
1193
+ tweet_data = response.data
1194
+ if isinstance(tweet_data, dict):
1195
+ return {
1196
+ 'data': {
1197
+ 'id': str(tweet_data.get('id')),
1198
+ 'text': tweet_data.get('text'),
1199
+ 'created_at': tweet_data.get('created_at')
1200
+ }
1201
+ }
1202
+ else:
1203
+ return {
1204
+ 'data': {
1205
+ 'id': str(tweet_data.id),
1206
+ 'text': tweet_data.text,
1207
+ 'created_at': tweet_data.created_at.isoformat() if hasattr(tweet_data, 'created_at') else None
1208
+ }
1209
+ }
1210
+ return None
1211
+
1212
+ except Exception as e:
1213
+ self.logger.error(f"Error posting tweet: {str(e)}", exc_info=True)
1214
+ return None
1215
+
1216
+ async def get_user_profile(self) -> Optional[Dict]:
1217
+ """Get the authenticated user's profile.
1218
+
1219
+ Returns:
1220
+ Dictionary containing user profile data or None if failed
1221
+ """
1222
+ try:
1223
+ response = await self._make_request(
1224
+ func=self.client.get_me,
1225
+ endpoint_type='users',
1226
+ user_fields=['id', 'name', 'username', 'description', 'public_metrics']
1227
+ )
1228
+
1229
+ if response and hasattr(response, 'data'):
1230
+ user_data = response.data
1231
+ return {
1232
+ 'data': {
1233
+ 'id': str(user_data.id),
1234
+ 'name': user_data.name,
1235
+ 'username': user_data.username,
1236
+ 'description': user_data.description,
1237
+ 'public_metrics': getattr(user_data, 'public_metrics', {})
1238
+ }
1239
+ }
1240
+ return None
1241
+
1242
+ except Exception as e:
1243
+ self.logger.error(f"Error getting user profile: {str(e)}", exc_info=True)
1244
+ return None
1245
+
1246
+ async def get_user_following(self, user_id: str, max_results: int = 100) -> Optional[Dict]:
1247
+ """Get list of users that the specified user follows.
1248
+
1249
+ Args:
1250
+ user_id: User ID to get following list for
1251
+ max_results: Maximum number of results to return
1252
+
1253
+ Returns:
1254
+ Dictionary containing following user data or None if failed
1255
+ """
1256
+ try:
1257
+ response = await self._make_request(
1258
+ func=self.client.get_users_following,
1259
+ endpoint_type='users',
1260
+ id=user_id,
1261
+ max_results=max_results,
1262
+ user_fields=['id', 'name', 'username', 'description', 'public_metrics']
1263
+ )
1264
+
1265
+ if response and hasattr(response, 'data'):
1266
+ following_data = []
1267
+ for user in response.data:
1268
+ following_data.append({
1269
+ 'id': str(user.id),
1270
+ 'name': user.name,
1271
+ 'username': user.username,
1272
+ 'description': user.description,
1273
+ 'public_metrics': getattr(user, 'public_metrics', {})
1274
+ })
1275
+
1276
+ return {
1277
+ 'data': following_data,
1278
+ 'meta': {
1279
+ 'result_count': len(following_data)
1280
+ }
1281
+ }
1282
+ return None
1283
+
1284
+ except Exception as e:
1285
+ self.logger.error(f"Error getting user following: {str(e)}", exc_info=True)
1286
+ return None
1287
+
1288
+ async def get_own_user_id(self) -> Optional[str]:
1289
+ """Alias for get_authenticated_user_id() to maintain compatibility.
1290
+
1291
+ Returns:
1292
+ String containing the user ID or None if failed
1293
+ """
1294
+ return await self.get_authenticated_user_id()
1295
+
1296
+ async def search(
1297
+ self,
1298
+ query: str,
1299
+ max_results: int = 10,
1300
+ include_replies: bool = False,
1301
+ **kwargs
1302
+ ) -> List[Dict[str, Any]]:
1303
+ """Search for tweets.
1304
+
1305
+ Args:
1306
+ query: Search query
1307
+ max_results: Maximum number of results to return (must be between 10 and 100)
1308
+ include_replies: Whether to include replies
1309
+ **kwargs: Additional search parameters
1310
+
1311
+ Returns:
1312
+ List of tweet dictionaries
1313
+
1314
+ Raises:
1315
+ APIError: If search fails
1316
+ ConfigurationError: If service is not enabled
1317
+ ValueError: If max_results is not between 10 and 100
1318
+ """
1319
+ if not self._enabled:
1320
+ raise ConfigurationError("Twitter service is not enabled - missing credentials")
1321
+
1322
+ # Validate max_results
1323
+ if max_results < 10:
1324
+ self.logger.warning(f"Adjusting max_results from {max_results} to minimum allowed value of 10")
1325
+ max_results = 10
1326
+ elif max_results > 100:
1327
+ self.logger.warning(f"Adjusting max_results from {max_results} to maximum allowed value of 100")
1328
+ max_results = 100
1329
+
1330
+ await self._ensure_initialized()
1331
+
1332
+ try:
1333
+ # Build query
1334
+ if not include_replies:
1335
+ query = f"{query} -is:reply"
1336
+
1337
+ # Execute search with rate limit handling
1338
+ try:
1339
+ response = await self._make_request(
1340
+ func=self.client.search_recent_tweets,
1341
+ endpoint_type='search',
1342
+ query=query,
1343
+ max_results=max_results,
1344
+ tweet_fields=['created_at', 'public_metrics', 'entities'],
1345
+ expansions=['author_id'],
1346
+ user_fields=['username', 'name', 'profile_image_url'],
1347
+ **kwargs
1348
+ )
1349
+
1350
+ # Format response
1351
+ tweets = []
1352
+ users = {user.id: user for user in response.includes['users']} if response.includes else {}
1353
+
1354
+ for tweet in response.data or []:
1355
+ author = users.get(tweet.author_id)
1356
+ tweets.append({
1357
+ 'id': tweet.id,
1358
+ 'text': tweet.text,
1359
+ 'created_at': tweet.created_at.isoformat() if hasattr(tweet, 'created_at') else None,
1360
+ 'metrics': tweet.public_metrics,
1361
+ 'author': {
1362
+ 'id': author.id,
1363
+ 'username': author.username,
1364
+ 'name': author.name,
1365
+ 'profile_image_url': author.profile_image_url
1366
+ } if author else None,
1367
+ 'entities': tweet.entities
1368
+ })
1369
+
1370
+ # If original max_results was less than 10, truncate results
1371
+ if len(tweets) > max_results:
1372
+ tweets = tweets[:max_results]
1373
+
1374
+ return tweets
1375
+
1376
+ except tweepy.errors.TooManyRequests as e:
1377
+ # Extract reset time from headers
1378
+ reset_time = None
1379
+ if hasattr(e, 'response') and hasattr(e.response, 'headers'):
1380
+ reset_time = e.response.headers.get('x-rate-limit-reset')
1381
+ wait_time = int(reset_time) - int(time.time()) if reset_time else 900
1382
+
1383
+ # Raise RateLimitError instead of sleeping
1384
+ raise RateLimitError(f"Twitter rate limit exceeded. Wait time: {wait_time} seconds")
1385
+
1386
+ except Exception as e:
1387
+ if isinstance(e, RateLimitError):
1388
+ raise
1389
+ self.logger.error(f"Twitter search error: {str(e)}")
1390
+ raise APIError(f"Twitter search failed: {str(e)}")
1391
+
1392
+ async def get_user(self, username: str) -> Dict[str, Any]:
1393
+ """Get user information.
1394
+
1395
+ Args:
1396
+ username: Twitter username
1397
+
1398
+ Returns:
1399
+ User information dictionary
1400
+
1401
+ Raises:
1402
+ APIError: If user lookup fails
1403
+ """
1404
+ await self._ensure_initialized()
1405
+
1406
+ try:
1407
+ response = self.client.get_user(
1408
+ username=username,
1409
+ user_fields=['description', 'public_metrics', 'profile_image_url']
1410
+ )
1411
+
1412
+ if not response.data:
1413
+ raise APIError(f"User {username} not found")
1414
+
1415
+ user = response.data
1416
+ return {
1417
+ 'id': user.id,
1418
+ 'username': user.username,
1419
+ 'name': user.name,
1420
+ 'description': user.description,
1421
+ 'metrics': user.public_metrics,
1422
+ 'profile_image_url': user.profile_image_url
1423
+ }
1424
+
1425
+ except tweepy.TweepyException as e:
1426
+ raise APIError(f"Twitter user lookup failed: {str(e)}")
1427
+ except Exception as e:
1428
+ raise APIError(f"Error during Twitter user lookup: {str(e)}")
1429
+
1430
+ async def get_tweets(
1431
+ self,
1432
+ user_id: str,
1433
+ max_results: int = 10,
1434
+ **kwargs
1435
+ ) -> List[Dict[str, Any]]:
1436
+ """Get tweets from a user.
1437
+
1438
+ Args:
1439
+ user_id: Twitter user ID
1440
+ max_results: Maximum number of tweets to return
1441
+ **kwargs: Additional parameters
1442
+
1443
+ Returns:
1444
+ List of tweet dictionaries
1445
+
1446
+ Raises:
1447
+ APIError: If tweet lookup fails
1448
+ """
1449
+ await self._ensure_initialized()
1450
+
1451
+ try:
1452
+ response = self.client.get_users_tweets(
1453
+ id=user_id,
1454
+ max_results=max_results,
1455
+ tweet_fields=['created_at', 'public_metrics', 'entities'],
1456
+ **kwargs
1457
+ )
1458
+
1459
+ tweets = []
1460
+ for tweet in response.data or []:
1461
+ tweets.append({
1462
+ 'id': tweet.id,
1463
+ 'text': tweet.text,
1464
+ 'created_at': tweet.created_at.isoformat(),
1465
+ 'metrics': tweet.public_metrics,
1466
+ 'entities': tweet.entities
1467
+ })
1468
+
1469
+ return tweets
1470
+
1471
+ except tweepy.TweepyException as e:
1472
+ raise APIError(f"Twitter tweets lookup failed: {str(e)}")
1473
+ except Exception as e:
1474
+ raise APIError(f"Error during Twitter tweets lookup: {str(e)}")
1475
+
1476
+ # =====================================================================
1477
+ # G1 — FULL write surface: v1.1 client, helpers, gating, actions
1478
+ # =====================================================================
1479
+
1480
+ def _init_v1_client(self) -> None:
1481
+ """Build a v1.1 ``tweepy.API`` (OAuth1.0a) for media upload. Fail-open."""
1482
+ try:
1483
+ if not (self.api_key and self.api_secret and self.access_token and self.access_token_secret):
1484
+ self.api_v1 = None
1485
+ return
1486
+ auth = tweepy.OAuth1UserHandler(
1487
+ self.api_key, self.api_secret, self.access_token, self.access_token_secret
1488
+ )
1489
+ self.api_v1 = tweepy.API(auth)
1490
+ except Exception as e: # pragma: no cover - defensive
1491
+ self.api_v1 = None
1492
+ self.logger.warning(f"Twitter v1.1 API (media) unavailable: {e}")
1493
+
1494
+ # --- safety knobs ----------------------------------------------------
1495
+
1496
+ @staticmethod
1497
+ def _env_int(name: str, default: int) -> int:
1498
+ try:
1499
+ return int(os.getenv(name, str(default)))
1500
+ except (TypeError, ValueError):
1501
+ return default
1502
+
1503
+ def _write_cap(self) -> int:
1504
+ return self._env_int("TWITTER_WRITE_MAX_PER_HOUR", 15)
1505
+
1506
+ def _dm_cap(self) -> int:
1507
+ return self._env_int("TWITTER_DM_MAX_PER_HOUR", 5)
1508
+
1509
+ def _require_approval(self) -> bool:
1510
+ return os.getenv("TWITTER_REQUIRE_APPROVAL", "true").strip().lower() not in _FALSEY
1511
+
1512
+ def _rate_available(self, *, is_dm: bool) -> bool:
1513
+ now = time.time()
1514
+ bucket = self._dm_times if is_dm else self._write_times
1515
+ cutoff = now - 3600
1516
+ bucket[:] = [t for t in bucket if t >= cutoff]
1517
+ cap = self._dm_cap() if is_dm else self._write_cap()
1518
+ return len(bucket) < cap
1519
+
1520
+ def _rate_record(self, *, is_dm: bool) -> None:
1521
+ (self._dm_times if is_dm else self._write_times).append(time.time())
1522
+
1523
+ async def _precheck_write(self, action_name: str, params, execution_context,
1524
+ *, is_dm: bool = False):
1525
+ """Rate-limit + approval gate. Returns an error ActionResult to block, or None to proceed."""
1526
+ if not self._rate_available(is_dm=is_dm):
1527
+ cap = self._dm_cap() if is_dm else self._write_cap()
1528
+ kind = "DMs" if is_dm else "writes"
1529
+ return self.create_action_result(
1530
+ error=f"Twitter rate limit reached: max {cap}/hour for {kind}. Try later.",
1531
+ include_in_memory=True,
1532
+ )
1533
+ if self._require_approval():
1534
+ approved = False
1535
+ try:
1536
+ from tools.controller.approval import get_approval_provider_or_deny, AutoApprover
1537
+ try:
1538
+ import tools.controller.approval_interactive # noqa: F401 # register interactive_cli
1539
+ except Exception:
1540
+ pass
1541
+ # H9: fail-CLOSED on an unknown provider; and don't SILENTLY auto-approve —
1542
+ # TWITTER_REQUIRE_APPROVAL with APPROVAL_PROVIDER unset resolves to AutoApprover
1543
+ # (approves everything). Warn loudly so an operator relying on approval knows the
1544
+ # write is proceeding with no human gate.
1545
+ provider = get_approval_provider_or_deny(os.getenv("APPROVAL_PROVIDER"))
1546
+ if isinstance(provider, AutoApprover):
1547
+ self.logger.warning(
1548
+ f"⚠️ Twitter write '{action_name}' auto-approved: TWITTER_REQUIRE_APPROVAL "
1549
+ f"is on but APPROVAL_PROVIDER is unset/auto (no human gate). Set "
1550
+ f"APPROVAL_PROVIDER=interactive_cli for a real prompt."
1551
+ )
1552
+ timeout = float(os.getenv("APPROVAL_TIMEOUT_SEC", "30"))
1553
+ pdict = params.model_dump() if hasattr(params, "model_dump") else dict(params or {})
1554
+ approved = await asyncio.wait_for(
1555
+ provider.request(action_name, pdict, execution_context), timeout=timeout
1556
+ )
1557
+ except Exception as e: # timeout / provider error → fail-closed deny
1558
+ self.logger.warning(f"twitter approval denied (error) for {action_name}: {e}")
1559
+ approved = False
1560
+ if not approved:
1561
+ return self.create_action_result(
1562
+ error=f"Twitter write '{action_name}' blocked: approval denied.",
1563
+ include_in_memory=True,
1564
+ )
1565
+ self._rate_record(is_dm=is_dm)
1566
+ return None
1567
+
1568
+ # --- internal write helpers -----------------------------------------
1569
+
1570
+ async def _upload_media(self, media_paths: List[str]) -> List[str]:
1571
+ """Upload local media via v1.1 and return media_id strings."""
1572
+ if not getattr(self, "api_v1", None):
1573
+ raise RuntimeError("media upload requires the v1.1 API client (OAuth1.0a creds)")
1574
+ ids: List[str] = []
1575
+ for path in media_paths:
1576
+ media = await self._make_request(
1577
+ func=self.api_v1.media_upload, endpoint_type="media", filename=path
1578
+ )
1579
+ mid = getattr(media, "media_id", None) or getattr(media, "media_id_string", None)
1580
+ ids.append(str(mid))
1581
+ return ids
1582
+
1583
+ @staticmethod
1584
+ def _tweet_from_response(resp) -> Dict[str, Any]:
1585
+ if not resp or not hasattr(resp, "data") or not resp.data:
1586
+ return {}
1587
+ data = resp.data
1588
+ if isinstance(data, dict):
1589
+ return {"id": str(data.get("id")), "text": data.get("text")}
1590
+ return {"id": str(getattr(data, "id", "")), "text": getattr(data, "text", None)}
1591
+
1592
+ async def _compose_tweet(self, *, text: str, media_paths: Optional[List[str]] = None,
1593
+ poll_options: Optional[List[str]] = None,
1594
+ poll_duration_minutes: Optional[int] = None,
1595
+ in_reply_to_tweet_id: Optional[str] = None,
1596
+ quote_tweet_id: Optional[str] = None) -> Dict[str, Any]:
1597
+ kwargs: Dict[str, Any] = {"text": text}
1598
+ if media_paths:
1599
+ kwargs["media_ids"] = await self._upload_media(media_paths)
1600
+ if poll_options:
1601
+ kwargs["poll_options"] = list(poll_options)
1602
+ if poll_duration_minutes:
1603
+ kwargs["poll_duration_minutes"] = int(poll_duration_minutes)
1604
+ if in_reply_to_tweet_id:
1605
+ kwargs["in_reply_to_tweet_id"] = in_reply_to_tweet_id
1606
+ if quote_tweet_id:
1607
+ kwargs["quote_tweet_id"] = quote_tweet_id
1608
+ resp = await self._make_request(func=self.client.create_tweet, endpoint_type="tweets", **kwargs)
1609
+ return self._tweet_from_response(resp)
1610
+
1611
+ async def _resolve_user_id(self, user: str) -> Optional[str]:
1612
+ """Return a numeric user id; pass digit strings through, else resolve username."""
1613
+ if str(user).isdigit():
1614
+ return str(user)
1615
+ info = await self.get_user_by_identifier(user)
1616
+ if info and info.get("id"):
1617
+ return str(info["id"])
1618
+ return None
1619
+
1620
+ @staticmethod
1621
+ def _split_tweet_text(text: str, limit: int = _TWEET_MAX) -> List[str]:
1622
+ """Split text into ≤``limit``-char parts at word boundaries, numbered (i/n).
1623
+
1624
+ P6: the do-what-a-human-would-do fallback for over-long compositions —
1625
+ a single part is returned unchanged; multiple parts each carry an
1626
+ " (i/n)" counter and every numbered part fits the wire limit.
1627
+ """
1628
+ text = (text or "").strip()
1629
+ if len(text) <= limit:
1630
+ return [text]
1631
+ reserve = 9 # room for " (99/99)"
1632
+ chunk_limit = max(1, limit - reserve)
1633
+ parts: List[str] = []
1634
+ cur = ""
1635
+ for word in text.split():
1636
+ # hard-break pathological words longer than a whole chunk
1637
+ while len(word) > chunk_limit:
1638
+ if cur:
1639
+ parts.append(cur)
1640
+ cur = ""
1641
+ parts.append(word[:chunk_limit])
1642
+ word = word[chunk_limit:]
1643
+ if not cur:
1644
+ cur = word
1645
+ elif len(cur) + 1 + len(word) <= chunk_limit:
1646
+ cur += " " + word
1647
+ else:
1648
+ parts.append(cur)
1649
+ cur = word
1650
+ if cur:
1651
+ parts.append(cur)
1652
+ n = len(parts)
1653
+ if n == 1:
1654
+ return parts
1655
+ return [f"{p} ({i}/{n})" for i, p in enumerate(parts, 1)]
1656
+
1657
+ async def _compose_thread(self, parts: List[str], *,
1658
+ media_paths: Optional[List[str]] = None,
1659
+ in_reply_to_tweet_id: Optional[str] = None,
1660
+ quote_tweet_id: Optional[str] = None,
1661
+ poll_options: Optional[List[str]] = None,
1662
+ poll_duration_minutes: Optional[int] = None) -> List[str]:
1663
+ """Post ``parts`` as a chained thread; media/poll/quote ride the head tweet."""
1664
+ prev_id = in_reply_to_tweet_id
1665
+ ids: List[str] = []
1666
+ for i, part in enumerate(parts):
1667
+ tweet = await self._compose_tweet(
1668
+ text=part,
1669
+ media_paths=media_paths if i == 0 else None,
1670
+ poll_options=poll_options if i == 0 else None,
1671
+ poll_duration_minutes=poll_duration_minutes if i == 0 else None,
1672
+ quote_tweet_id=quote_tweet_id if i == 0 else None,
1673
+ in_reply_to_tweet_id=prev_id,
1674
+ )
1675
+ prev_id = tweet.get("id")
1676
+ ids.append(str(prev_id))
1677
+ return ids
1678
+
1679
+ def _ok(self, msg: str):
1680
+ return self.create_action_result(extracted_content=msg, include_in_memory=True)
1681
+
1682
+ def _err(self, msg: str):
1683
+ return self.create_action_result(error=msg, include_in_memory=True)
1684
+
1685
+ def _check_ready(self):
1686
+ if not self._enabled:
1687
+ return self._err("Twitter service not available - missing credentials")
1688
+ if not twitter_write_enabled():
1689
+ return self._err("Twitter write surface disabled (set TWITTER_ENABLED=true)")
1690
+ return None
1691
+
1692
+ # --- compose actions -------------------------------------------------
1693
+
1694
+ @BaseTool.action("Post a tweet (optionally with media and/or a poll).", param_model=TwitterPostAction)
1695
+ async def twitter_post(self, params: TwitterPostAction, execution_context=None):
1696
+ notready = self._check_ready()
1697
+ if notready:
1698
+ return notready
1699
+ block = await self._precheck_write("twitter_post", params, execution_context)
1700
+ if block:
1701
+ return block
1702
+ try:
1703
+ parts = self._split_tweet_text(params.text)
1704
+ if len(parts) == 1:
1705
+ tweet = await self._compose_tweet(
1706
+ text=parts[0], media_paths=params.media_paths,
1707
+ poll_options=params.poll_options, poll_duration_minutes=params.poll_duration_minutes,
1708
+ )
1709
+ return self._ok(f"🐦 Posted tweet {tweet.get('id')}")
1710
+ ids = await self._compose_thread(
1711
+ parts, media_paths=params.media_paths,
1712
+ poll_options=params.poll_options, poll_duration_minutes=params.poll_duration_minutes,
1713
+ )
1714
+ return self._ok(
1715
+ f"🐦 Text exceeded 280 chars — posted as a {len(ids)}-tweet thread: {', '.join(ids)}"
1716
+ )
1717
+ except Exception as e:
1718
+ return self._err(f"Error posting tweet: {e}")
1719
+
1720
+ @BaseTool.action("Reply to a tweet (optionally with media).", param_model=TwitterReplyAction)
1721
+ async def twitter_reply(self, params: TwitterReplyAction, execution_context=None):
1722
+ notready = self._check_ready()
1723
+ if notready:
1724
+ return notready
1725
+ block = await self._precheck_write("twitter_reply", params, execution_context)
1726
+ if block:
1727
+ return block
1728
+ try:
1729
+ parts = self._split_tweet_text(params.text)
1730
+ if len(parts) == 1:
1731
+ tweet = await self._compose_tweet(
1732
+ text=parts[0], media_paths=params.media_paths,
1733
+ in_reply_to_tweet_id=params.tweet_id,
1734
+ )
1735
+ return self._ok(f"🐦 Replied with tweet {tweet.get('id')}")
1736
+ ids = await self._compose_thread(
1737
+ parts, media_paths=params.media_paths,
1738
+ in_reply_to_tweet_id=params.tweet_id,
1739
+ )
1740
+ return self._ok(
1741
+ f"🐦 Reply exceeded 280 chars — posted as a {len(ids)}-tweet reply thread: {', '.join(ids)}"
1742
+ )
1743
+ except Exception as e:
1744
+ return self._err(f"Error replying: {e}")
1745
+
1746
+ @BaseTool.action("Quote-tweet an existing tweet.", param_model=TwitterQuoteAction)
1747
+ async def twitter_quote(self, params: TwitterQuoteAction, execution_context=None):
1748
+ notready = self._check_ready()
1749
+ if notready:
1750
+ return notready
1751
+ block = await self._precheck_write("twitter_quote", params, execution_context)
1752
+ if block:
1753
+ return block
1754
+ try:
1755
+ parts = self._split_tweet_text(params.text)
1756
+ if len(parts) == 1:
1757
+ tweet = await self._compose_tweet(text=parts[0], quote_tweet_id=params.tweet_id)
1758
+ return self._ok(f"🐦 Quoted tweet {tweet.get('id')}")
1759
+ # head tweet quotes; the remainder chains as a reply thread
1760
+ ids = await self._compose_thread(parts, quote_tweet_id=params.tweet_id)
1761
+ return self._ok(
1762
+ f"🐦 Quote exceeded 280 chars — posted as a {len(ids)}-tweet thread: {', '.join(ids)}"
1763
+ )
1764
+ except Exception as e:
1765
+ return self._err(f"Error quoting: {e}")
1766
+
1767
+ @BaseTool.action("Post a thread: a list of tweets chained as replies.", param_model=TwitterThreadAction)
1768
+ async def twitter_thread(self, params: TwitterThreadAction, execution_context=None):
1769
+ notready = self._check_ready()
1770
+ if notready:
1771
+ return notready
1772
+ block = await self._precheck_write("twitter_thread", params, execution_context)
1773
+ if block:
1774
+ return block
1775
+ try:
1776
+ prev_id = None
1777
+ ids: List[str] = []
1778
+ for i, text in enumerate(params.texts):
1779
+ tweet = await self._compose_tweet(
1780
+ text=text,
1781
+ media_paths=params.media_paths if i == 0 else None,
1782
+ in_reply_to_tweet_id=prev_id,
1783
+ )
1784
+ prev_id = tweet.get("id")
1785
+ ids.append(str(prev_id))
1786
+ return self._ok(f"🐦 Posted thread of {len(ids)} tweets: {', '.join(ids)}")
1787
+ except Exception as e:
1788
+ return self._err(f"Error posting thread: {e}")
1789
+
1790
+ @BaseTool.action("Delete one of your tweets.", param_model=TwitterDeleteAction)
1791
+ async def twitter_delete_tweet(self, params: TwitterDeleteAction, execution_context=None):
1792
+ notready = self._check_ready()
1793
+ if notready:
1794
+ return notready
1795
+ block = await self._precheck_write("twitter_delete_tweet", params, execution_context)
1796
+ if block:
1797
+ return block
1798
+ try:
1799
+ await self._make_request(func=self.client.delete_tweet, endpoint_type="tweets", id=params.tweet_id)
1800
+ return self._ok(f"🐦 Deleted tweet {params.tweet_id}")
1801
+ except Exception as e:
1802
+ return self._err(f"Error deleting tweet: {e}")
1803
+
1804
+ # --- engagement actions ---------------------------------------------
1805
+
1806
+ async def _engage(self, action_name: str, func_name: str, id_kwarg: str,
1807
+ tweet_id: str, params, execution_context):
1808
+ notready = self._check_ready()
1809
+ if notready:
1810
+ return notready
1811
+ block = await self._precheck_write(action_name, params, execution_context)
1812
+ if block:
1813
+ return block
1814
+ try:
1815
+ # id_kwarg differs per endpoint: tweepy uses ``tweet_id`` for like/retweet
1816
+ # but ``source_tweet_id`` for unretweet (verified vs tweepy 4.14).
1817
+ await self._make_request(func=getattr(self.client, func_name),
1818
+ endpoint_type="tweets", **{id_kwarg: tweet_id})
1819
+ return self._ok(f"🐦 {action_name} ok for {tweet_id}")
1820
+ except Exception as e:
1821
+ return self._err(f"Error in {action_name}: {e}")
1822
+
1823
+ @BaseTool.action("Like a tweet.", param_model=TwitterTweetIdAction)
1824
+ async def twitter_like(self, params: TwitterTweetIdAction, execution_context=None):
1825
+ return await self._engage("twitter_like", "like", "tweet_id", params.tweet_id, params, execution_context)
1826
+
1827
+ @BaseTool.action("Unlike a tweet.", param_model=TwitterTweetIdAction)
1828
+ async def twitter_unlike(self, params: TwitterTweetIdAction, execution_context=None):
1829
+ return await self._engage("twitter_unlike", "unlike", "tweet_id", params.tweet_id, params, execution_context)
1830
+
1831
+ @BaseTool.action("Retweet a tweet.", param_model=TwitterTweetIdAction)
1832
+ async def twitter_retweet(self, params: TwitterTweetIdAction, execution_context=None):
1833
+ return await self._engage("twitter_retweet", "retweet", "tweet_id", params.tweet_id, params, execution_context)
1834
+
1835
+ @BaseTool.action("Remove a retweet.", param_model=TwitterTweetIdAction)
1836
+ async def twitter_unretweet(self, params: TwitterTweetIdAction, execution_context=None):
1837
+ return await self._engage("twitter_unretweet", "unretweet", "source_tweet_id", params.tweet_id, params, execution_context)
1838
+
1839
+ # --- relationship actions -------------------------------------------
1840
+
1841
+ async def _relate(self, action_name: str, func_name: str, user: str, params, execution_context):
1842
+ notready = self._check_ready()
1843
+ if notready:
1844
+ return notready
1845
+ block = await self._precheck_write(action_name, params, execution_context)
1846
+ if block:
1847
+ return block
1848
+ try:
1849
+ uid = await self._resolve_user_id(user)
1850
+ if not uid:
1851
+ return self._err(f"Could not resolve user '{user}'")
1852
+ await self._make_request(func=getattr(self.client, func_name),
1853
+ endpoint_type="users", target_user_id=uid)
1854
+ return self._ok(f"🐦 {action_name} ok for {user}")
1855
+ except Exception as e:
1856
+ return self._err(f"Error in {action_name}: {e}")
1857
+
1858
+ @BaseTool.action("Follow a user.", param_model=TwitterUserAction)
1859
+ async def twitter_follow(self, params: TwitterUserAction, execution_context=None):
1860
+ return await self._relate("twitter_follow", "follow_user", params.user, params, execution_context)
1861
+
1862
+ @BaseTool.action("Unfollow a user.", param_model=TwitterUserAction)
1863
+ async def twitter_unfollow(self, params: TwitterUserAction, execution_context=None):
1864
+ return await self._relate("twitter_unfollow", "unfollow_user", params.user, params, execution_context)
1865
+
1866
+ @BaseTool.action("Mute a user.", param_model=TwitterUserAction)
1867
+ async def twitter_mute(self, params: TwitterUserAction, execution_context=None):
1868
+ return await self._relate("twitter_mute", "mute", params.user, params, execution_context)
1869
+
1870
+ @BaseTool.action("Block a user.", param_model=TwitterUserAction)
1871
+ async def twitter_block(self, params: TwitterUserAction, execution_context=None):
1872
+ return await self._relate("twitter_block", "block", params.user, params, execution_context)
1873
+
1874
+ # --- DM action -------------------------------------------------------
1875
+
1876
+ @BaseTool.action("Send a direct message to a user.", param_model=TwitterDMAction)
1877
+ async def twitter_dm(self, params: TwitterDMAction, execution_context=None):
1878
+ notready = self._check_ready()
1879
+ if notready:
1880
+ return notready
1881
+ block = await self._precheck_write("twitter_dm", params, execution_context, is_dm=True)
1882
+ if block:
1883
+ return block
1884
+ try:
1885
+ uid = await self._resolve_user_id(params.recipient)
1886
+ if not uid:
1887
+ return self._err(f"Could not resolve recipient '{params.recipient}'")
1888
+ await self._make_request(func=self.client.create_direct_message, endpoint_type="dm",
1889
+ participant_id=uid, text=params.text)
1890
+ return self._ok(f"🐦 DM sent to {params.recipient}")
1891
+ except Exception as e:
1892
+ return self._err(f"Error sending DM: {e}")
1893
+
1894
+ # --- act-on-context reads (always available) ------------------------
1895
+
1896
+ @BaseTool.action("Get recent mentions of your own account.", param_model=TwitterMentionsAction)
1897
+ async def twitter_get_mentions(self, params: TwitterMentionsAction, execution_context=None):
1898
+ if not self._enabled:
1899
+ return self._err("Twitter service not available - missing credentials")
1900
+ try:
1901
+ me_id = await self.get_authenticated_user_id()
1902
+ if not me_id:
1903
+ return self._err("Could not resolve authenticated user id")
1904
+ resp = await self._make_request(func=self.client.get_users_mentions, endpoint_type="tweets",
1905
+ id=me_id, max_results=params.max_results,
1906
+ tweet_fields=["created_at", "text", "author_id"])
1907
+ items = []
1908
+ if resp and getattr(resp, "data", None):
1909
+ items = [{"id": str(t.id), "text": t.text} for t in resp.data]
1910
+ return self._ok(f"🐦 Mentions:\n{json.dumps(items, indent=2)}")
1911
+ except Exception as e:
1912
+ return self._err(f"Error getting mentions: {e}")
1913
+
1914
+ @BaseTool.action("Show your own authenticated Twitter profile.", param_model=TwitterWhoamiAction)
1915
+ async def twitter_whoami(self, params: TwitterWhoamiAction, execution_context=None):
1916
+ if not self._enabled:
1917
+ return self._err("Twitter service not available - missing credentials")
1918
+ try:
1919
+ profile = await self.get_user_profile()
1920
+ return self._ok(f"🐦 You are:\n{json.dumps(profile, indent=2)}")
1921
+ except Exception as e:
1922
+ return self._err(f"Error getting profile: {e}")
1923
+
1924
+ def get_actions(self) -> Dict[str, Any]:
1925
+ """Expose actions; hide the WRITE surface unless TWITTER_ENABLED=true.
1926
+
1927
+ Reads (search/get_user/get_tweets/mentions/whoami) are always available.
1928
+ Default-OFF: with the flag unset the write actions are absent — byte-identical
1929
+ to the pre-G1 surface.
1930
+ """
1931
+ actions = super().get_actions()
1932
+ if not twitter_write_enabled():
1933
+ for name in _TWITTER_WRITE_ACTIONS:
1934
+ actions.pop(name, None)
1935
+ return actions
1936
+
1937
+ async def close(self) -> None:
1938
+ """Cleanup method."""
1939
+ self._initialized = False
1940
+ self.client = None
1941
+ self.api_v1 = None
1942
+
1943
+ async def _ensure_initialized(self) -> None:
1944
+ """Ensure service is initialized."""
1945
+ if not self._initialized:
1946
+ await self._initialize()
1947
+
1948
+ @BaseTool.action("Search for tweets on Twitter", param_model=TwitterSearchActionModel)
1949
+ async def twitter_search(self, params: TwitterSearchActionModel):
1950
+ """Search for tweets on Twitter.
1951
+
1952
+ Args:
1953
+ params: Twitter search parameters
1954
+
1955
+ Returns:
1956
+ ActionResult containing search results
1957
+ """
1958
+ try:
1959
+ if not self._enabled:
1960
+ return self.create_action_result(
1961
+ error="Twitter service not available - missing credentials",
1962
+ include_in_memory=True
1963
+ )
1964
+
1965
+ search_results = await self.search(
1966
+ query=params.query,
1967
+ max_results=params.max_results,
1968
+ include_replies=params.include_replies
1969
+ )
1970
+
1971
+ msg = f'🐦 Twitter search results for "{params.query}":\n{json.dumps(search_results, indent=2)}'
1972
+ self.logger.info(f'Twitter search performed for: {params.query}')
1973
+ return self.create_action_result(
1974
+ extracted_content=msg,
1975
+ include_in_memory=True
1976
+ )
1977
+ except Exception as e:
1978
+ error_msg = f"Error performing Twitter search: {str(e)}"
1979
+ self.logger.error(error_msg)
1980
+ return self.create_action_result(
1981
+ error=error_msg,
1982
+ include_in_memory=True
1983
+ )
1984
+
1985
+ @BaseTool.action("Get Twitter user information", param_model=TwitterGetUserActionModel)
1986
+ async def twitter_get_user(self, params: TwitterGetUserActionModel):
1987
+ """Get Twitter user information.
1988
+
1989
+ Args:
1990
+ params: Twitter user parameters
1991
+
1992
+ Returns:
1993
+ ActionResult containing user information
1994
+ """
1995
+ try:
1996
+ if not self._enabled:
1997
+ return self.create_action_result(
1998
+ error="Twitter service not available - missing credentials",
1999
+ include_in_memory=True
2000
+ )
2001
+
2002
+ user_info = await self.get_user_by_identifier(params.username)
2003
+ if not user_info:
2004
+ return self.create_action_result(
2005
+ error=f"Twitter user {params.username} not found",
2006
+ include_in_memory=True
2007
+ )
2008
+
2009
+ msg = f'🐦 Twitter user information for "{params.username}":\n{json.dumps(user_info, indent=2)}'
2010
+ self.logger.info(f'Twitter user info retrieved for: {params.username}')
2011
+ return self.create_action_result(
2012
+ extracted_content=msg,
2013
+ include_in_memory=True
2014
+ )
2015
+ except Exception as e:
2016
+ error_msg = f"Error getting Twitter user: {str(e)}"
2017
+ self.logger.error(error_msg)
2018
+ return self.create_action_result(
2019
+ error=error_msg,
2020
+ include_in_memory=True
2021
+ )
2022
+
2023
+ @BaseTool.action("Get tweets from a Twitter user", param_model=TwitterGetTweetsActionModel)
2024
+ async def twitter_get_tweets(self, params: TwitterGetTweetsActionModel):
2025
+ """Get tweets from a Twitter user.
2026
+
2027
+ Args:
2028
+ params: Twitter tweets parameters
2029
+
2030
+ Returns:
2031
+ ActionResult containing tweets
2032
+ """
2033
+ try:
2034
+ if not self._enabled:
2035
+ return self.create_action_result(
2036
+ error="Twitter service not available - missing credentials",
2037
+ include_in_memory=True
2038
+ )
2039
+
2040
+ tweets = await self.get_user_timeline(
2041
+ username_or_id=params.user_id,
2042
+ max_results=params.max_results
2043
+ )
2044
+
2045
+ if not tweets:
2046
+ return self.create_action_result(
2047
+ error=f"No tweets found for user ID {params.user_id}",
2048
+ include_in_memory=True
2049
+ )
2050
+
2051
+ msg = f'🐦 Tweets from user ID {params.user_id}:\n{json.dumps(tweets, indent=2)}'
2052
+ self.logger.info(f'Twitter tweets retrieved for user ID: {params.user_id}')
2053
+ return self.create_action_result(
2054
+ extracted_content=msg,
2055
+ include_in_memory=True
2056
+ )
2057
+ except Exception as e:
2058
+ error_msg = f"Error getting tweets: {str(e)}"
2059
+ self.logger.error(error_msg)
2060
+ return self.create_action_result(
2061
+ error=error_msg,
2062
+ include_in_memory=True
2063
+ )
2064
+
2065
+ def create_action_result(self, extracted_content=None, error=None, include_in_memory=False, is_done=False):
2066
+ """Create a properly structured action result.
2067
+
2068
+ This helper method ensures consistent action results.
2069
+ """
2070
+ try:
2071
+ # Import ActionResult from canonical location
2072
+ from tools.controller.types import ActionResult
2073
+ return ActionResult(
2074
+ extracted_content=extracted_content,
2075
+ error=error,
2076
+ include_in_memory=include_in_memory,
2077
+ is_done=is_done
2078
+ )
2079
+ except ImportError:
2080
+ # Fallback to a dictionary if ActionResult can't be imported
2081
+ return {
2082
+ "extracted_content": extracted_content,
2083
+ "error": error,
2084
+ "include_in_memory": include_in_memory,
2085
+ "is_done": is_done
2086
+ }