You could hash the current stack state, require the hash be in some OP_RETURN, then execute whatever arbitrary user-provided code. After it’s done, your code hashes the stack state again and compares it against the same OP_RETURN to verify the user didn’t mess up your stack.
Or, you could just have the user-provided code be the last segment of your script, and have *VERIFY
OP just before it.