Agent-related refactoring and bugfixes