# Refactor Proposal for `agent_run()` in `src/agent.c` ## Current State The `agent_run()` function is highly complex, handling multiple responsibilities such as response parsing, tool execution, context management, and response accumulation. Its length and nested logic make it difficult to read, maintain, and test. ## Proposed Refactor Break down `agent_run()` into smaller, focused functions: ### 1. `process_response()` - Parses the JSON response. - Determines the next steps based on response content. - Handles context overflow and retries. ### 2. `execute_tools()` - Executes tools when indicated by the response. - Manages tool call results and message updates. ### 3. `handle_incomplete_response()` - Checks if the response is incomplete. - Initiates continuation requests if needed. ### 4. `finalize_response()` - Finalizes the accumulated response. - Cleans up resources. ## Benefits - Improved readability and maintainability. - Easier to write unit tests for individual components. - Clear separation of concerns. ## Implementation The implementation involves extracting code blocks from `agent_run()` into these functions, passing necessary context as parameters, and replacing the original code with calls to these functions. This modularization will significantly enhance the code quality and facilitate future extensions or modifications. --- This proposal will be used as the basis for the refactoring process.