You'll need a looping script. Use the command behaviour to detect the behaviour of the loon in question. Then do what you want: setCaptive true/false is probably your best bet.
Maybe something like this. Not guaranteed.
#loop
? not (alive loon1): exit
loon1 setCaptive true
? behaviour loon1 == "aware": loon1 setCaptive false
? behaviour loon1 == "stealth": loon1 setCaptive false
~3
goto "loop"