I wanted to add such logic in default config for kamailio as well (not mangle contact if not first proxy), but forgot about it, I'll do it soon. There is a new function is_first_hop() in devel version, for older version the solution is to store the number of record-route headers for request and compare with the number of them in response.