Error in sink(type = "output") : invalid connection on Mac OS

This suggests that this isn’t a Stan issue, but a more general issue compiling code. Your Mac’s C++ standard library headers aren’t being found. So I think this is a system toolchain / Xcode Command Line Tools issue. It might be worth installing the command line tools again. You can open the terminal and run

xcode-select --install

Or did you do that already?

I’m a little rusty debugging toolchain issues like this, but if compilation still fails after that then can you share what’s in your Makevars file? You can view it using:

usethis::edit_r_makevars()

And also what’s the output from running the commands below?

# What kind of Mac CPU do you have
Sys.info()[["machine"]]
R.version$arch

# Where macOS thinks the developer tools are
system2("xcode-select", "-p", stdout = TRUE, stderr = TRUE)

# Where the macOS SDK is (this is where headers like <cmath> live)
system2("xcrun", "--show-sdk-path", stdout = TRUE, stderr = TRUE)

# Check if the <cmath> header exists inside that SDK
sdk <- system2("xcrun", "--show-sdk-path", stdout = TRUE)
file.exists(file.path(sdk, "usr/include/c++/v1/cmath"))