In buildings, the thermal functions of heating, ventilation, air conditioning and domestic hot water production are often interdependent. Additionally, it is more and more complex to control them, given the increasing use of alternative energy sources, such as solar thermal collectors or heatpumps. In this work, we propose an approach allowing to design and optimize the control of thermal systems in the buildings, while improving flexibility and reusability. Consumer, producer, distributor and environmental agents are used to represent the building and its appliances. These agents' internal models allow them to compute the energy needs, energy resources and associated costs, and take into account the specificities of the thermal systems. Following this modeling step, a distributed mechanism automatically controls the system, by combining a multi-criteria selection, a local optimization and a distributed allocation of the available resources. This approach was used to control a compact unit providing heating, ventilation and domestic hot water production in a low-energy building. The system was evaluated using a thermal simulator, and managed to improve the thermal comfort by 35% compared to the initial control system, for only a 2.5% increase in costs.