How to transform world space vertex to camera space position in Cycles OSL
for transforming the position you should use point type because according to the OSL Language Specs :


  Depending on the type of the passed point p, different transformation
  semantics will be used. A point will transform as a position, a vector
  as a direction without regard to positioning


just change the type of the Position variable to point or use the P variable that holds the current position then use the transform function as you did ; even after that the whole objects will be bright white, so i have tried to normalize the Z coordinate  using two variables which act as near and far planes that limits the depth range :

shader depth_shader(
    float minZ = 0,
    float maxZ = 1,
    output closure color Color = emission())
{
    point lP = transform("camera", P);
    float Z = lP[2];
    if( (Z&gt;minZ) &amp;&amp; (Z&lt;maxZ))
        Z = (Z-minZ)/(maxZ-minZ);
    else 
        Z = 0;
    Color= color(Z, Z, Z) * emission();    
}