Main Agent Module Refactoring
Summary
Refactored src/tunacode/core/agents/main.py from 641 lines to 389 lines (39% reduction) by extracting focused modules and removing dead code.
Changes
New Files Created
history_preparer.py-HistoryPreparerclass- Encapsulates message history preparation logic
- Handles pruning, cleanup, and sanitization
- Single
prepare()method returns ready-to-use history
request_logger.py- Logging utilitieslog_history_state()- Logs message history for diagnosticslog_sanitized_history_state()- Logs sanitized history in debug modelog_run_handle_context_messages()- Logs pydantic-ai contextlog_node_details()- Logs node type informationmessage_has_tool_calls()- Helper for detecting tool calls
Removed Dead Code
DotDictclass - Unused utility classcolorsvariable - Never referencedIterationManagerclass - Trivially simple, inlined into_handle_iteration_node()
Cleaned Up
EmptyResponseHandler.prompt_action()- Replaced inlineStateProxyclass with@dataclass StateView- Simplified counter tracking logic in
EmptyResponseHandler.track()
Rationale
The original main.py had accumulated multiple responsibilities:
- Request initialization
- Message history preparation (7+ methods)
- Logging (7+ methods)
- Agent iteration loop
- Node handling
- Abort cleanup
This violated single responsibility principle and made the file difficult to navigate.
Architecture Compliance
All new modules follow layer dependency rules:
coremodules only import fromtools,utils,types, andinfrastructure- No imports from
uilayer
Verified by passing tests/architecture/test_layer_dependencies.py.
Updated Documentation
docs/codebase-map/modules/core-agents.md- Updated exports and component listdocs/architecture/agent-loop.md- Updated line references and file list