The foundational question — what the congregation says while the prayer leader recites Modim — is taken up directly in the Gemara (Sotah 40a), which records a dispute among Tannaim and Amoraim: Rav holds they say 'We give thanks to You, Lord our God, for the merit of giving thanks to You'; Shmuel says 'God of all living flesh, for the merit of giving thanks to You'; Rabbi Simai says 'Our Creator, Who created everything in the beginning'; the Sages of Neharde'a in his name add 'We offer blessings and praises to Your great name, for You have given us life and sustained us'; and Rav Acha bar Yaakov rounds it off with a plea for continued life, grace, and the ingathering of exiles.
The operative ruling drawn from this Talmudic passage is cited by the Beit Yosef (Orach Chayim 127:5), who quotes Rashi's gloss on 'for the merit of giving thanks to You' — meaning that God has placed in our hearts the impulse to acknowledge and cleave to Him — and notes that Rav Pappa concluded from all these opinions that one should say all of them together, which is precisely the composite text we know as Modim D'rabanan.
The Tur (Orach Chayim 127) similarly records this Talmudic practice, framing the reason a congregant must bow and recite this text: since the individual is in the middle of his own silent Amidah when the leader reaches Modim, he must at minimum bow and say the congregational Modim, lest he appear like one who denies the thanksgiving, and the Tur further specifies at which points during the individual's own prayer it is appropriate to bow.
The Rambam (Mishneh Torah, Prayer and the Priestly Blessing 9:4) codifies the full text the congregation recites — 'We give thanks to You, God our Lord and Lord of all flesh, our Creator and the Creator of all existence; blessings and thanks to Your great and holy name, for You have granted us life and sustained us; so may You continue to grant us life and sustain us, and gather our exiles into the courtyards of Your Sanctuary' — reflecting the composite drawn from all the Amoraic opinions, and instructs that the people bow slightly but not excessively when the prayer leader bows at Modim.