Agents can only possess a person plugged into the Matrix (a "bluepill"):
[Agents] can move in and out of any software still hard wired to their system. That means that anyone we haven't unplugged is potentially an Agent.
Morpheus, The Matrix
Zion operatives, however, hack into the Matrix via a wireless signal that they broadcast from their hoverships in the real world. We know this is a wireless signal because the hoverships are seen fleeing sentinels while Zion operatives are jacked into the Matrix (e.g. near the end of The Matrix, when the Nebuchadnezzar is nearly destroyed by sentinels before Neo is able to jack out of the Matrix).
Therefore, the Agents can determine if someone is plugged into the Matrix by whether or not they can possess him. More simply, the Agents can determine if someone is plugged into the Matrix by looking for a wired connection to that person. In the specific case where Trinity escaped just before the garbage truck (driven by Agent Smith) hit her: Agent Smith was able to determine that there was no wired connection to Trinity and that he could not possess her. Consequently, he possessed someone nearby who was hard wired to the Matrix (the bluepill driver of the garbage truck) instead.
[W]ouldn't anyone at any time change into an Agent, meaning that they could not mingle with anyone that was still plugged into the Matrix?
To answer this, I will borrow from my answer to a question about the purpose of the bug used by the Agents:
Agents can "see" what any bluepill sees but since there are billions of bluepills it is impossible to look in real time at what all of them are seeing to pinpoint the location of Zion operatives anywhere in the Matrix. This exhaustive search can only be narrowed down if a bluepill sees something unusual (e.g. an operative breaking the rules of the Matrix) and/or if Agents know the rough location of the operatives (such as when they are in a chase, in which case they can check only what is seen by the relatively few bluepills in that area). In the case of the vagrant in the subway, the Agents had been chasing Neo and Trinity so they knew roughly where they were; they undoubtedly checked what the vagrant saw (especially since he was in view of a phone the operatives could use to jack out) and Agent Smith possessed him when he recognized Neo and Trinity.
It's not that the Agents' method of determining whether or not someone is plugged in is inaccurate: it's that there are far too many connections (bluepills) to monitor them all in real time. The Agents require some means of narrowing down the number of connections to check (an anomaly, like a supernatural ability exhibited by a Zion operative). Zion operatives can safely "mingle" with bluepills in the Matrix so long as they don't do anything unusual which draws the attention of the system.