You can check the value of the $CARRIER system variable to determine if you have a connection or not. A value of 1 indicates a connection has been made, while zero means the connection is idle. You could have a script that ran all of the time that looked something like this:
proc main
when $CARRIER call check_carrier
while 1
yield
endwhile
endproc
proc check_carrier
if $CARRIER == 1
execute main_script
endif
endproc
What this script would do is sit in an endless loop until the value of $CARRIER changed. When this happened, the check_carrier procedure would be called. If the value of $CARRIER is one, indicating a connection, the script that provides the main functionality (called main_script above, but you can give it whatever name you wish) is executed. When main_script has finished executing, control would return back to the script above until the next call. You will need to do some error handling in main_script to make sure the script exits if $CARRIER is unexpectedly lost. You could use the same check_carrier script, just modified a little bit:
proc check_carrier
if $CARRIER == 0
exit
endif
endproc
Before the exit command, you may need to do some additional cleanup, such as closing any open files your main script might have open and so on.