I have been trying to trigger screen mirroring when remotely signing into macOS and watching for the agent ScreensharingAgent to launch, run, etc so I can have it switch all external monitors to mirror the main monitor but not having any luck.
Environment:
macOS 12.3 / MBP 16" 2020 Intel.
Keyboard Maestro Version 10.0.1
Configuration
System runs 24/7; never sleeps
Account locks after disconnecting a remote session.
Clarification of how Screen Sharing Session works. - Link.
After reviewing the above answer and some experimenting found a partially working solution. Configuration
Disable checkbox "Always show Remote Management status in menu bar" in System Preferences > Sharing,
In Keyboard Maestro conditional if/else settings
2a. This Application: SSMenuAgent.app is "is running but not at the front"
That is the trigger setting that will show the Menu when someone is observing the mac. Additionally, I added a secondary check to make sure the "Screens Connection" agent is running (it only launches during an active session), keeping those two options conditional to ALL allows for both local network and remote connecting to trigger the mirroring. And prevents the trigger when Apple Support connects.
When something works in Terminal but not in a KM action it's usually because you don't have the same PATH environment variables in both. To find the correct path, in Terminal type which <utilityName> -- in this case, which displayplacer.
I'm guessing you installed displayplacer with Homebrew -- in which case you should know that Homebrew has a different (more correct!) base install path on M1 processors than for the old Intels. It is now /opt/homebrew/bin, so you can probably change the start of the second line of your script to /opt/homebrew/bin/displayplacer.