On my 2015 MacBook you could just tell it not to sleep while charging in settings. Then the screen would turn off when in clamshell but you could still connect to it via ssh or screen sharing and it would be running. I used to use this to run stock market charting software all day and be able to view/interact from my iPad.
System Preferences -> Battery -> Power Adapter -> Prevent computer from sleeping when the display is off (checked)
This has always only been an option while charging; not on battery.
[Edit] This seems to be acting differently on my M1 Air. I can still SSH in, and it appears to continue to run my apps, but I cannot seem to access it via Screen Sharing unless I open the lid. I have a market app that lists each transaction and I can see it continues to update; as there are many transactions per minute. But I wonder why I cannot Screen Share. Hmmm...