I think it's simpler to let your agent print what should happen after the execution. That way you are sure it ran before doing anything else. In the past I let the agent print some javascript (embedded in html) to close the window from which the agent was executed.
Martin Vereecken
http://www.bizzybee.be (Notes blog)