refactor out commong logic between agent and plugin

refactor out commong logic between agent and plugin