Refactor Plan for agent_run() in src/agent.c
Overview
The agent_run() function is a core component responsible for orchestrating the agent's lifecycle, including message handling, API communication, error handling, and recursive task management. Its length and complexity hinder maintainability and readability.
Proposed Refactor
To improve the code quality, the function will be split into smaller, focused functions:
1. build_request()
- Purpose: Construct the JSON payload for the API request.
- Benefits: Isolates request construction, making it easier to modify and test.
2. process_response()
- Purpose: Handle the API response, including parsing, error detection, and extracting the choice.
- Benefits: Separates response handling logic, simplifies main loop.
3. handle_tool_calls()
- Purpose: Manage execution of tool calls, including calling tools and integrating results.
- Benefits: Encapsulates tool execution, improves clarity.
4. check_incomplete_response()
- Purpose: Detect if the response indicates incomplete work, triggering context shrinking.
- Benefits: Isolates heuristic checks, makes main loop cleaner.
5. perform_iteration()
- Purpose: Encapsulate one iteration of the agent loop, calling the above functions.
- Benefits: Modularizes iteration logic, facilitates retries and control flow.
Rationale
This refactor aims to:
- Enhance readability and maintainability.
- Facilitate unit testing of individual components.
- Simplify control flow and error handling.
Implementation
The implementation will involve creating these functions in src/agent.c and replacing the main loop in agent_run() with calls to perform_iteration() until completion or error.
This plan will be executed in the next step.