Perhaps the same way virus did so... and before cellular organisms evolved. Remember there are many kinds of virus (single or double stranded DNA or RNA) This is a such a basic question as how the first polymeric organic molecules evolved; then surrounded by membranes, then... voila, we appeared. But be sure: a good start to find answers is to learn making the right questions. Yours is a very good one.
This is a good question and related to evolution of life. To solve this question that how plasmid evolved first we should see that how DNA evolved? The evolution of plasmids may based on the requirement of small circular DNA molecule which contains Ori C and replication machinery those can transmit from one organism to other organism through Horizontal Gene Transfer... for more detail you can visit below link ....
Small portions of genome can be excised from bacterial genome (described in: The Stealth Episome: Suppression of Gene Expression on the Excised Genomic Island PPHGI-1 from Pseudomonas syringae pv. phaseolicola Scott A. C. Godfrey, Helen C. Lovell, John W. Mansfield, David S. Corry, Robert W. Jackson, Dawn L. Arnold
PLoS Pathog. 2011 March; 7(3): e1002010.) and exist in bacteria for certain time. I think this is a general mechanism that can give origin self-replicating episomes = plasmids.