Perhaps you could use something based on
HTTP::Daemon.
merlyn has a few excellent
articles on his web site doing something similar using
Chatbot::Eliza. Check out the articles with a title like "Doctor is IN", namely
Column 23 and
Column 24.
The idea is that you have one script that starts out as a CGI, which contains the actual state, and which launches its own small webserver — and keeps running in the background. That one takes over for this session, processing all following requests from the browser, and all in the context of the current application.