Build a Coding Agent
Stage 7 of 7v1 · 4a69d88d

The Autonomous ReAct Loop

Orchestrate the complete loop of reasoning, tool execution, workspace updating, and controlled termination.

The Engine of Coding Agents: The ReAct Loop

The ReAct (Reasoning + Acting) paradigm powers agents like Claude Code, Codex, Pi, and OpenCode. Rather than producing code in a single blind shot, the agent operates in an iterative feedback loop:

  1. Thought: The model inspects project state and devises an immediate next step.
  2. Action: The model calls a tool (read_file, write_file, patch_file, or finish).
  3. Observation: The runtime executes the tool against the workspace and reports the result.
  4. Iteration: The loop repeats until the model calls finish or the safety limit (max_steps) is reached.

Input and Output Protocol

Input on stdin:

{
  "op": "run_agent",
  "task": "Fix bug in calc.py",
  "max_steps": 5,
  "workspace": {
    "calc.py": "def add(a, b):\n    return a - b\n"
  },
  "model_turns": [
    {
      "thought": "I will read calc.py.",
      "action": { "tool": "read_file", "args": { "path": "calc.py" } }
    },
    {
      "thought": "I will patch the operator.",
      "action": {
        "tool": "patch_file",
        "args": {
          "path": "calc.py",
          "old_str": "return a - b",
          "new_str": "return a + b"
        }
      }
    },
    {
      "thought": "Task is done.",
      "action": { "tool": "finish", "args": { "message": "Operator fixed." } }
    }
  ]
}

Successful output on stdout (compact JSON with sorted keys):

{
  "final_message": "Operator fixed.",
  "status": "completed",
  "steps": 3,
  "workspace": { "calc.py": "def add(a, b):\n    return a + b\n" }
}

Required fields:

  • final_message: the final message from the finish action (or step limit message).
  • status: "completed" upon normal completion, or "max_steps_exceeded" when step limit is hit.
  • steps: total number of steps executed.
  • workspace: final state of the workspace reflecting all modifications.

Termination and Safety Rules

  • When action.tool === "finish", immediately terminate with status "completed".
  • If max_steps are executed without calling finish, stop cleanly with status "max_steps_exceeded" and final_message: "Maximum steps reached".
  • Each tool execution updates the workspace cumulatively for subsequent steps.

Acceptance Criteria

  • Sequentially drives model turns through the tool dispatcher.
  • Persists workspace mutations across turns.
  • Terminates cleanly with "completed" when finish is called.
  • Halts with "max_steps_exceeded" when max_steps is reached.