Coverage for bot/autonomy_runtime.py: 89%
102 statements
« prev ^ index » next coverage.py v7.10.7, created at 2026-02-25 12:32 -0300
« prev ^ index » next coverage.py v7.10.7, created at 2026-02-25 12:32 -0300
1import asyncio
2import threading
3from collections.abc import Awaitable, Callable
4from concurrent.futures import TimeoutError as FutureTimeoutError
5from typing import Any
7from bot.autonomy_logic import process_autonomy_goal
8from bot.control_plane import RISK_AUTO_CHAT, RISK_SUGGEST_STREAMER, control_plane
9from bot.observability import observability
10from bot.runtime_config import logger
11from bot.sentiment_engine import sentiment_engine
13AutoChatDispatcher = Callable[[str], Awaitable[None]]
16class AutonomyRuntime:
17 def __init__(self) -> None:
18 self._lock = threading.Lock()
19 self._loop: asyncio.AbstractEventLoop | None = None
20 self._loop_task: asyncio.Task[Any] | None = None
21 self._tick_lock: asyncio.Lock | None = None
22 self._auto_chat_dispatcher: AutoChatDispatcher | None = None
23 self._mode = "eventsub"
25 def bind(
26 self,
27 *,
28 loop: asyncio.AbstractEventLoop,
29 mode: str,
30 auto_chat_dispatcher: AutoChatDispatcher | None = None,
31 ) -> None:
32 with self._lock:
33 self._loop = loop
34 self._mode = (mode or "eventsub").strip().lower() or "eventsub"
35 self._auto_chat_dispatcher = auto_chat_dispatcher
36 loop.call_soon_threadsafe(self._ensure_loop_task)
38 def unbind(self) -> None:
39 with self._lock:
40 task = self._loop_task
41 self._loop = None
42 self._loop_task = None
43 self._tick_lock = None
44 self._auto_chat_dispatcher = None
45 self._mode = "eventsub"
46 if task is not None:
47 task.cancel()
48 control_plane.set_loop_running(False)
50 def _ensure_loop_task(self) -> None:
51 with self._lock:
52 loop = self._loop
53 task = self._loop_task
54 if loop is None or loop.is_closed():
55 return
56 if task is not None and not task.done():
57 return
59 created_task = loop.create_task(self._heartbeat_loop())
60 with self._lock:
61 if self._loop is loop:
62 self._loop_task = created_task
63 else:
64 created_task.cancel()
66 async def _heartbeat_loop(self) -> None:
67 control_plane.set_loop_running(True)
68 try:
69 while True:
70 with self._lock:
71 active_loop = self._loop
72 if active_loop is None or active_loop is not asyncio.get_running_loop():
73 break
75 try:
76 await self._run_tick(force=False, reason="heartbeat")
77 except Exception as error:
78 logger.error("Autonomy heartbeat falhou: %s", error)
79 control_plane.register_dispatch_failure(f"heartbeat_error:{error}")
80 observability.record_error(
81 category="autonomy_heartbeat",
82 details=str(error),
83 )
85 heartbeat_seconds = int(
86 control_plane.get_config().get("heartbeat_interval_seconds", 60)
87 )
88 await asyncio.sleep(max(15, heartbeat_seconds))
89 except asyncio.CancelledError:
90 raise
91 finally:
92 control_plane.set_loop_running(False)
94 async def _run_tick(self, *, force: bool, reason: str) -> dict[str, Any]:
95 if self._tick_lock is None:
96 self._tick_lock = asyncio.Lock()
97 async with self._tick_lock:
98 control_plane.touch_heartbeat()
99 control_plane.register_tick(reason=reason)
101 due_goals = control_plane.consume_due_goals(force=force)
103 # Dynamic sentiment triggers (Phase 8)
104 if not force:
105 if sentiment_engine.should_trigger_anti_boredom():
106 due_goals.append(
107 {
108 "id": "dynamic-anti-boredom",
109 "name": "Gatilho Anti-Tédio",
110 "risk": RISK_AUTO_CHAT,
111 "prompt": "O chat está pouco engajado ou 'morno'. Puxe um assunto interessante ou faça uma pergunta instigante para os viewers.",
112 }
113 )
114 if sentiment_engine.should_trigger_anti_confusion():
115 due_goals.append(
116 {
117 "id": "dynamic-anti-confusion",
118 "name": "Gatilho Anti-Confusão",
119 "risk": RISK_SUGGEST_STREAMER,
120 "prompt": "O chat parece confuso com o que está acontecendo. Sugira ao streamer explicar melhor a situação atual ou o objetivo do jogo.",
121 }
122 )
124 processed: list[dict[str, Any]] = []
126 dispatcher = self._get_auto_chat_dispatcher()
127 for goal in due_goals:
128 processed.append(await process_autonomy_goal(goal, dispatcher))
130 return {
131 "ok": True,
132 "reason": reason,
133 "force": bool(force),
134 "due_goals": len(due_goals),
135 "processed": processed,
136 "runtime": control_plane.runtime_snapshot(),
137 }
139 def _get_auto_chat_dispatcher(self) -> AutoChatDispatcher | None:
140 with self._lock:
141 return self._auto_chat_dispatcher
143 def run_manual_tick(self, *, force: bool = True, reason: str = "manual") -> dict[str, Any]:
144 coroutine = self._run_tick(force=force, reason=reason)
145 with self._lock:
146 loop = self._loop
147 if loop is None or loop.is_closed() or not loop.is_running():
148 return asyncio.run(coroutine)
150 future = asyncio.run_coroutine_threadsafe(coroutine, loop)
151 try:
152 return future.result(timeout=20.0)
153 except FutureTimeoutError as error:
154 future.cancel()
155 raise TimeoutError("Autonomy tick timeout.") from error
158autonomy_runtime = AutonomyRuntime()
160__all__ = ["AutonomyRuntime", "autonomy_runtime"]