"""ReAct (Reason + Act) loop — the core agent execution engine. Each iteration: 1. REASON — CoT produces a thought chain for the current task 2. ACT — Select and call the appropriate tool 3. OBSERVE — Read the tool's output 4. REFLECT — Decide to continue, retry, or backtrack Design reference: - Claude Opus: patient, thorough observation before next action - GPT Codex: tight code-execute-fix feedback loop - Gemini Pro: explicit state tracking across iterations """ from __future__ import annotations import logging import os import time from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any, Callable from agent.core.chain_of_thought import ChainOfThoughtReasoner from agent.core.planner import Task, TaskGraph, TaskStatus if TYPE_CHECKING: from agent.memory.audit_log import AuditLog from agent.memory.short_term import ShortTermMemory from agent.tools.base import BaseTool LOGGER = logging.getLogger(__name__) try: from prometheus_client import Counter, Histogram REACT_TASKS_TOTAL = Counter( "zenex_react_tasks_total", "Total number of task executions in React loop", ["tool", "status"], ) REACT_TOOL_SECONDS = Histogram( "zenex_react_tool_seconds", "Tool execution duration in seconds", ["tool"], buckets=(0.05, 0.1, 0.25, 0.5, 1, 2, 5, 10, 30, 60), ) except Exception: # pragma: no cover - metrics optional REACT_TASKS_TOTAL = None REACT_TOOL_SECONDS = None MAX_REACT_ITERATIONS = 50 # global guard MAX_TASK_RETRIES = 3 MAX_RETRY_BACKOFF_SECONDS = 5.0 @dataclass class Observation: """Result of a tool call.""" tool: str args: dict stdout: str = "" stderr: str = "" exit_code: int = 0 elapsed: float = 0.0 success: bool = True error: str = "" @property def summary(self) -> str: if not self.success: return f"[FAIL] {self.tool}: {self.error or self.stderr[:200]}" return f"[OK] {self.tool}: {(self.stdout or '').strip()[:200]}" @dataclass class ReactStep: """A single Reason→Act→Observe step recorded in the loop.""" iteration: int task_id: str thought: str action: str tool: str tool_args: dict observation: Observation timestamp: float = field(default_factory=time.time) class ReactLoop: """Main agent execution loop. Runs the Reason→Act→Observe cycle until the task graph is done or a hard limit is hit. On task failure it retries up to MAX_TASK_RETRIES times with re-planning before giving up. """ def __init__( self, tools: dict[str, "BaseTool"], memory: "ShortTermMemory", audit_log: "AuditLog", router: Any = None, should_cancel: Callable[[], bool] | None = None, ) -> None: self.tools = tools self.memory = memory self.audit = audit_log self.router = router # ModelRouter — available for future code-gen steps self.should_cancel = should_cancel self.reasoner = ChainOfThoughtReasoner() self.history: list[ReactStep] = [] self._retry_backoff = float(os.environ.get("ZENEX_RETRY_BACKOFF", "0.5")) # ------------------------------------------------------------------ # Public API # ------------------------------------------------------------------ def run(self, graph: TaskGraph) -> bool: """Execute the full task graph. Returns True if all tasks succeeded.""" LOGGER.info("ReactLoop starting for: %s", graph.goal) iteration = 0 while not graph.is_done() and iteration < MAX_REACT_ITERATIONS: if self._is_cancelled(): LOGGER.warning("ReactLoop cancellation requested. Stopping execution.") return False iteration += 1 ready = graph.ready_tasks() if not ready: if graph.has_failures(): LOGGER.warning("No runnable tasks — some tasks failed permanently.") break LOGGER.warning("No ready tasks but graph not done — possible cycle.") break for task in ready: if self._is_cancelled(): LOGGER.warning("Cancellation requested before task '%s'.", task.title) return False self._execute_task(task, graph, iteration) success = not graph.has_failures() LOGGER.info("ReactLoop done. success=%s iterations=%d", success, iteration) return success # ------------------------------------------------------------------ # Internal helpers # ------------------------------------------------------------------ def _execute_task(self, task: Task, graph: TaskGraph, iteration: int) -> None: task.status = TaskStatus.IN_PROGRESS task.attempts += 1 # 1. REASON cot = self.reasoner.reason( goal=task.description, context=self.memory.context_summary(), available_tools=list(self.tools.keys()), history=[{"action": s.action, "observation": s.observation.summary} for s in self.history[-5:]], ) cot.chosen_tool = task.tool if task.tool in self.tools else self._pick_tool(task) cot.chosen_action = f"Run {cot.chosen_tool} for task '{task.title}'" LOGGER.info( "[iter=%d] Task '%s' → tool=%s (attempt %d/%d)", iteration, task.title, cot.chosen_tool, task.attempts, task.max_attempts, ) # 2. ACT observation = self._call_tool(cot.chosen_tool, task, graph) # 3. OBSERVE step = ReactStep( iteration=iteration, task_id=task.id, thought=cot.conclusion, action=cot.chosen_action, tool=cot.chosen_tool, tool_args=task.tool_args, observation=observation, ) self.history.append(step) self.audit.record(step) self.memory.update(task, observation) # 4. REFLECT if observation.success: graph.mark_complete(task.id, result=observation.stdout[:500]) LOGGER.info(" ✓ Task '%s' completed.", task.title) if REACT_TASKS_TOTAL: REACT_TASKS_TOTAL.labels(tool=cot.chosen_tool, status="success").inc() else: failure_type = self._classify_failure(observation) self.memory.set("last_failure_type", failure_type) LOGGER.warning(" ✗ Task '%s' failed (%s): %s", task.title, failure_type, observation.error) # Failure-specific backoff reduces flapping on external/transient failures. if task.attempts < task.max_attempts: delay = min(MAX_RETRY_BACKOFF_SECONDS, self._retry_backoff * (2 ** (task.attempts - 1))) if failure_type == "external": delay = min(MAX_RETRY_BACKOFF_SECONDS, delay * 2) time.sleep(delay) # Retry: mark_failed increments counter; if < max_attempts it resets to PENDING graph.mark_failed(task.id) if task.failed_permanently: LOGGER.error(" Task '%s' exceeded max retries.", task.title) skipped = graph.skip_downstream_of(task.id) if skipped: LOGGER.warning( " Skipped %d downstream task(s) blocked by '%s'.", len(skipped), task.title, ) if REACT_TASKS_TOTAL: REACT_TASKS_TOTAL.labels(tool=cot.chosen_tool, status="failure").inc() def _call_tool(self, tool_name: str, task: Task, graph: TaskGraph) -> Observation: tool = self.tools.get(tool_name) if tool is None: return Observation( tool=tool_name, args={}, success=False, error=f"Tool '{tool_name}' not registered.", ) t0 = time.time() try: # Enrich args with task context args = { **task.tool_args, "_task": task, "_graph": graph, "_memory": self.memory, "_audit": self.audit, "_should_cancel": self.should_cancel, } result = tool.run(args) elapsed = time.time() - t0 if REACT_TOOL_SECONDS: REACT_TOOL_SECONDS.labels(tool=tool_name).observe(elapsed) return Observation( tool=tool_name, args=task.tool_args, stdout=result.get("stdout", ""), stderr=result.get("stderr", ""), exit_code=result.get("exit_code", 0), elapsed=elapsed, success=result.get("success", True), error=result.get("error", ""), ) except Exception as exc: elapsed = time.time() - t0 if REACT_TOOL_SECONDS: REACT_TOOL_SECONDS.labels(tool=tool_name).observe(elapsed) return Observation( tool=tool_name, args=task.tool_args, success=False, error=str(exc), elapsed=elapsed, ) def _pick_tool(self, task: Task) -> str: """Fallback tool selection when task.tool is not registered.""" for keyword, tool_name in [ ("test", "test_runner"), ("lint", "linter"), ("install", "package_manager"), ("file", "filesystem"), ("git", "git"), ("readme", "readme_gen"), ("zip", "archiver"), ("search", "web_search"), ]: if keyword in task.title.lower() and tool_name in self.tools: return tool_name return "executor" def _is_cancelled(self) -> bool: return bool(self.should_cancel and self.should_cancel()) @staticmethod def _classify_failure(observation: Observation) -> str: stderr = (observation.stderr or "").lower() error = (observation.error or "").lower() text = f"{stderr} {error}" if any(x in text for x in ["timeout", "connection", "503", "429", "temporar"]): return "external" if any(x in text for x in ["syntaxerror", "typeerror", "nameerror", "assertionerror"]): return "code" if any(x in text for x in ["lint", "format", "mypy", "ruff", "eslint"]): return "quality" return "unknown"