Are there any animal mods which allow animals to stay in their pen, but automatically retrieve food if needed? I am tired of cows walking around base, which is causing dirt and is kind of annoying.
Just put their food in their pen ;) Or make their pen somewhere where they can graze.
I have hay, but not long enough to sustain any animal until the next harvest. Is it possible for animals to only eat grass if it's in their diet?
It's possible if you have enough grass ;) Though probably they may eat hay and other things, too, if it's in their allowed area. You can try Smarter Food Selection (https://ludeon.com/forums/index.php?topic=30708) if you want more control on what your animals (and colonists, and prisoners ;) ) eat (the B18 version is on Steam or Github: https://github.com/Wishmaster01/Smarter.food.selection/releases (https://github.com/Wishmaster01/Smarter.food.selection/releases)).
I sometimes make their whole pen a growing zone, set it to grass (Vegetable Garden mod), install some skylights (Dub's Skylights mod) and one or two small heaters.
I usually have way too many animals, but even during very long winters they rarely need any hay and I feel better because their barn is cozy.
Just make sure to use no other plants than grass for this, because they will always eat the whole plant so even haygrass wouldn't be worth it (growing time 7 days vs only 2.5 for grass).
Install animal husbandry mod. Its a must have for farmers!