Fix memory leaks in agent