Replace the sorting helpers with a slightly more idiomatic approach

Instead of using reflect, use non-generic helper functions which
work with indexes instead.
Fix unprotected access to agent.keys