diff --git a/apps/ccusage/config-schema.json b/apps/ccusage/config-schema.json index f51341e..bb5239e 100644 --- a/apps/ccusage/config-schema.json +++ b/apps/ccusage/config-schema.json @@ -75,7 +75,12 @@ "mode": { "default": "auto", "description": "Cost calculation mode.", - "enum": ["auto", "calculate", "display"], + "enum": [ + "auto", + "calculate", + "display", + "api" + ], "markdownDescription": "Cost calculation mode.", "type": "string" }, @@ -106,7 +111,10 @@ "order": { "default": "asc", "description": "Sort order.", - "enum": ["desc", "asc"], + "enum": [ + "desc", + "asc" + ], "markdownDescription": "Sort order.", "type": "string" }, @@ -241,7 +249,12 @@ "mode": { "default": "auto", "description": "Cost calculation mode.", - "enum": ["auto", "calculate", "display"], + "enum": [ + "auto", + "calculate", + "display", + "api" + ], "markdownDescription": "Cost calculation mode.", "type": "string" }, @@ -272,7 +285,10 @@ "order": { "default": "asc", "description": "Sort order.", - "enum": ["desc", "asc"], + "enum": [ + "desc", + "asc" + ], "markdownDescription": "Sort order.", "type": "string" }, @@ -407,7 +423,12 @@ "mode": { "default": "auto", "description": "Cost calculation mode.", - "enum": ["auto", "calculate", "display"], + "enum": [ + "auto", + "calculate", + "display", + "api" + ], "markdownDescription": "Cost calculation mode.", "type": "string" }, @@ -438,7 +459,10 @@ "order": { "default": "asc", "description": "Sort order.", - "enum": ["desc", "asc"], + "enum": [ + "desc", + "asc" + ], "markdownDescription": "Sort order.", "type": "string" }, @@ -576,7 +600,12 @@ "mode": { "default": "auto", "description": "Cost calculation mode.", - "enum": ["auto", "calculate", "display"], + "enum": [ + "auto", + "calculate", + "display", + "api" + ], "markdownDescription": "Cost calculation mode.", "type": "string" }, @@ -607,7 +636,10 @@ "order": { "default": "asc", "description": "Sort order.", - "enum": ["desc", "asc"], + "enum": [ + "desc", + "asc" + ], "markdownDescription": "Sort order.", "type": "string" }, @@ -750,7 +782,12 @@ }, "mode": { "description": "Cost calculation mode.", - "enum": ["auto", "calculate", "display"], + "enum": [ + "auto", + "calculate", + "display", + "api" + ], "markdownDescription": "Cost calculation mode.", "type": "string" }, @@ -776,7 +813,10 @@ }, "order": { "description": "Sort order.", - "enum": ["desc", "asc"], + "enum": [ + "desc", + "asc" + ], "markdownDescription": "Sort order.", "type": "string" }, @@ -924,7 +964,12 @@ }, "mode": { "description": "Cost calculation mode.", - "enum": ["auto", "calculate", "display"], + "enum": [ + "auto", + "calculate", + "display", + "api" + ], "markdownDescription": "Cost calculation mode.", "type": "string" }, @@ -950,7 +995,10 @@ }, "order": { "description": "Sort order.", - "enum": ["desc", "asc"], + "enum": [ + "desc", + "asc" + ], "markdownDescription": "Sort order.", "type": "string" }, @@ -1094,7 +1142,12 @@ "mode": { "default": "auto", "description": "Cost calculation mode.", - "enum": ["auto", "calculate", "display"], + "enum": [ + "auto", + "calculate", + "display", + "api" + ], "markdownDescription": "Cost calculation mode.", "type": "string" }, @@ -1125,7 +1178,10 @@ "order": { "default": "asc", "description": "Sort order.", - "enum": ["desc", "asc"], + "enum": [ + "desc", + "asc" + ], "markdownDescription": "Sort order.", "type": "string" }, @@ -1260,7 +1316,12 @@ "mode": { "default": "auto", "description": "Cost calculation mode.", - "enum": ["auto", "calculate", "display"], + "enum": [ + "auto", + "calculate", + "display", + "api" + ], "markdownDescription": "Cost calculation mode.", "type": "string" }, @@ -1291,7 +1352,10 @@ "order": { "default": "asc", "description": "Sort order.", - "enum": ["desc", "asc"], + "enum": [ + "desc", + "asc" + ], "markdownDescription": "Sort order.", "type": "string" }, @@ -1399,7 +1463,12 @@ "costSource": { "default": "auto", "description": "Source for statusline cost calculation.", - "enum": ["auto", "ccusage", "cc", "both"], + "enum": [ + "auto", + "ccusage", + "cc", + "both" + ], "markdownDescription": "Source for statusline cost calculation.", "type": "string" }, @@ -1451,7 +1520,12 @@ "visualBurnRate": { "default": "off", "description": "Visual burn-rate display mode.", - "enum": ["off", "emoji", "text", "emoji-text"], + "enum": [ + "off", + "emoji", + "text", + "emoji-text" + ], "markdownDescription": "Visual burn-rate display mode.", "type": "string" } @@ -1505,7 +1579,12 @@ }, "mode": { "description": "Cost calculation mode.", - "enum": ["auto", "calculate", "display"], + "enum": [ + "auto", + "calculate", + "display", + "api" + ], "markdownDescription": "Cost calculation mode.", "type": "string" }, @@ -1531,7 +1610,10 @@ }, "order": { "description": "Sort order.", - "enum": ["desc", "asc"], + "enum": [ + "desc", + "asc" + ], "markdownDescription": "Sort order.", "type": "string" }, @@ -1677,7 +1759,12 @@ }, "costSource": { "description": "Source for statusline cost calculation.", - "enum": ["auto", "ccusage", "cc", "both"], + "enum": [ + "auto", + "ccusage", + "cc", + "both" + ], "markdownDescription": "Source for statusline cost calculation.", "type": "string" }, @@ -1710,7 +1797,12 @@ }, "mode": { "description": "Cost calculation mode.", - "enum": ["auto", "calculate", "display"], + "enum": [ + "auto", + "calculate", + "display", + "api" + ], "markdownDescription": "Cost calculation mode.", "type": "string" }, @@ -1749,7 +1841,10 @@ }, "order": { "description": "Sort order.", - "enum": ["desc", "asc"], + "enum": [ + "desc", + "asc" + ], "markdownDescription": "Sort order.", "type": "string" }, @@ -1874,7 +1969,12 @@ }, "visualBurnRate": { "description": "Visual burn-rate display mode.", - "enum": ["off", "emoji", "text", "emoji-text"], + "enum": [ + "off", + "emoji", + "text", + "emoji-text" + ], "markdownDescription": "Visual burn-rate display mode.", "type": "string" } @@ -1947,7 +2047,12 @@ "mode": { "default": "auto", "description": "Cost calculation mode.", - "enum": ["auto", "calculate", "display"], + "enum": [ + "auto", + "calculate", + "display", + "api" + ], "markdownDescription": "Cost calculation mode.", "type": "string" }, @@ -1978,7 +2083,10 @@ "order": { "default": "asc", "description": "Sort order.", - "enum": ["desc", "asc"], + "enum": [ + "desc", + "asc" + ], "markdownDescription": "Sort order.", "type": "string" }, @@ -2113,7 +2221,12 @@ "mode": { "default": "auto", "description": "Cost calculation mode.", - "enum": ["auto", "calculate", "display"], + "enum": [ + "auto", + "calculate", + "display", + "api" + ], "markdownDescription": "Cost calculation mode.", "type": "string" }, @@ -2144,7 +2257,10 @@ "order": { "default": "asc", "description": "Sort order.", - "enum": ["desc", "asc"], + "enum": [ + "desc", + "asc" + ], "markdownDescription": "Sort order.", "type": "string" }, @@ -2279,7 +2395,12 @@ "mode": { "default": "auto", "description": "Cost calculation mode.", - "enum": ["auto", "calculate", "display"], + "enum": [ + "auto", + "calculate", + "display", + "api" + ], "markdownDescription": "Cost calculation mode.", "type": "string" }, @@ -2310,7 +2431,10 @@ "order": { "default": "asc", "description": "Sort order.", - "enum": ["desc", "asc"], + "enum": [ + "desc", + "asc" + ], "markdownDescription": "Sort order.", "type": "string" }, @@ -2448,7 +2572,12 @@ "mode": { "default": "auto", "description": "Cost calculation mode.", - "enum": ["auto", "calculate", "display"], + "enum": [ + "auto", + "calculate", + "display", + "api" + ], "markdownDescription": "Cost calculation mode.", "type": "string" }, @@ -2479,7 +2608,10 @@ "order": { "default": "asc", "description": "Sort order.", - "enum": ["desc", "asc"], + "enum": [ + "desc", + "asc" + ], "markdownDescription": "Sort order.", "type": "string" }, @@ -2617,7 +2749,12 @@ }, "mode": { "description": "Cost calculation mode.", - "enum": ["auto", "calculate", "display"], + "enum": [ + "auto", + "calculate", + "display", + "api" + ], "markdownDescription": "Cost calculation mode.", "type": "string" }, @@ -2643,7 +2780,10 @@ }, "order": { "description": "Sort order.", - "enum": ["desc", "asc"], + "enum": [ + "desc", + "asc" + ], "markdownDescription": "Sort order.", "type": "string" }, @@ -2712,7 +2852,11 @@ "speed": { "default": "auto", "description": "Codex speed normalization strategy.", - "enum": ["auto", "standard", "fast"], + "enum": [ + "auto", + "standard", + "fast" + ], "markdownDescription": "Codex speed normalization strategy.", "type": "string" }, @@ -2776,7 +2920,12 @@ }, "mode": { "description": "Cost calculation mode.", - "enum": ["auto", "calculate", "display"], + "enum": [ + "auto", + "calculate", + "display", + "api" + ], "markdownDescription": "Cost calculation mode.", "type": "string" }, @@ -2802,7 +2951,10 @@ }, "order": { "description": "Sort order.", - "enum": ["desc", "asc"], + "enum": [ + "desc", + "asc" + ], "markdownDescription": "Sort order.", "type": "string" }, @@ -2871,7 +3023,11 @@ "speed": { "default": "auto", "description": "Codex speed normalization strategy.", - "enum": ["auto", "standard", "fast"], + "enum": [ + "auto", + "standard", + "fast" + ], "markdownDescription": "Codex speed normalization strategy.", "type": "string" }, @@ -2935,7 +3091,12 @@ }, "mode": { "description": "Cost calculation mode.", - "enum": ["auto", "calculate", "display"], + "enum": [ + "auto", + "calculate", + "display", + "api" + ], "markdownDescription": "Cost calculation mode.", "type": "string" }, @@ -2961,7 +3122,10 @@ }, "order": { "description": "Sort order.", - "enum": ["desc", "asc"], + "enum": [ + "desc", + "asc" + ], "markdownDescription": "Sort order.", "type": "string" }, @@ -3030,7 +3194,11 @@ "speed": { "default": "auto", "description": "Codex speed normalization strategy.", - "enum": ["auto", "standard", "fast"], + "enum": [ + "auto", + "standard", + "fast" + ], "markdownDescription": "Codex speed normalization strategy.", "type": "string" }, @@ -3097,7 +3265,12 @@ }, "mode": { "description": "Cost calculation mode.", - "enum": ["auto", "calculate", "display"], + "enum": [ + "auto", + "calculate", + "display", + "api" + ], "markdownDescription": "Cost calculation mode.", "type": "string" }, @@ -3123,7 +3296,10 @@ }, "order": { "description": "Sort order.", - "enum": ["desc", "asc"], + "enum": [ + "desc", + "asc" + ], "markdownDescription": "Sort order.", "type": "string" }, @@ -3192,7 +3368,11 @@ "speed": { "default": "auto", "description": "Codex speed normalization strategy.", - "enum": ["auto", "standard", "fast"], + "enum": [ + "auto", + "standard", + "fast" + ], "markdownDescription": "Codex speed normalization strategy.", "type": "string" }, @@ -3269,7 +3449,12 @@ }, "mode": { "description": "Cost calculation mode.", - "enum": ["auto", "calculate", "display"], + "enum": [ + "auto", + "calculate", + "display", + "api" + ], "markdownDescription": "Cost calculation mode.", "type": "string" }, @@ -3295,7 +3480,10 @@ }, "order": { "description": "Sort order.", - "enum": ["desc", "asc"], + "enum": [ + "desc", + "asc" + ], "markdownDescription": "Sort order.", "type": "string" }, @@ -3443,7 +3631,12 @@ }, "mode": { "description": "Cost calculation mode.", - "enum": ["auto", "calculate", "display"], + "enum": [ + "auto", + "calculate", + "display", + "api" + ], "markdownDescription": "Cost calculation mode.", "type": "string" }, @@ -3469,7 +3662,10 @@ }, "order": { "description": "Sort order.", - "enum": ["desc", "asc"], + "enum": [ + "desc", + "asc" + ], "markdownDescription": "Sort order.", "type": "string" }, @@ -3613,7 +3809,12 @@ "mode": { "default": "auto", "description": "Cost calculation mode.", - "enum": ["auto", "calculate", "display"], + "enum": [ + "auto", + "calculate", + "display", + "api" + ], "markdownDescription": "Cost calculation mode.", "type": "string" }, @@ -3644,7 +3845,10 @@ "order": { "default": "asc", "description": "Sort order.", - "enum": ["desc", "asc"], + "enum": [ + "desc", + "asc" + ], "markdownDescription": "Sort order.", "type": "string" }, @@ -3779,7 +3983,12 @@ "mode": { "default": "auto", "description": "Cost calculation mode.", - "enum": ["auto", "calculate", "display"], + "enum": [ + "auto", + "calculate", + "display", + "api" + ], "markdownDescription": "Cost calculation mode.", "type": "string" }, @@ -3810,7 +4019,10 @@ "order": { "default": "asc", "description": "Sort order.", - "enum": ["desc", "asc"], + "enum": [ + "desc", + "asc" + ], "markdownDescription": "Sort order.", "type": "string" }, @@ -3918,7 +4130,12 @@ "costSource": { "default": "auto", "description": "Source for statusline cost calculation.", - "enum": ["auto", "ccusage", "cc", "both"], + "enum": [ + "auto", + "ccusage", + "cc", + "both" + ], "markdownDescription": "Source for statusline cost calculation.", "type": "string" }, @@ -3970,7 +4187,12 @@ "visualBurnRate": { "default": "off", "description": "Visual burn-rate display mode.", - "enum": ["off", "emoji", "text", "emoji-text"], + "enum": [ + "off", + "emoji", + "text", + "emoji-text" + ], "markdownDescription": "Visual burn-rate display mode.", "type": "string" } @@ -4024,7 +4246,12 @@ }, "mode": { "description": "Cost calculation mode.", - "enum": ["auto", "calculate", "display"], + "enum": [ + "auto", + "calculate", + "display", + "api" + ], "markdownDescription": "Cost calculation mode.", "type": "string" }, @@ -4050,7 +4277,10 @@ }, "order": { "description": "Sort order.", - "enum": ["desc", "asc"], + "enum": [ + "desc", + "asc" + ], "markdownDescription": "Sort order.", "type": "string" }, @@ -4210,7 +4440,12 @@ "mode": { "default": "auto", "description": "Cost calculation mode.", - "enum": ["auto", "calculate", "display"], + "enum": [ + "auto", + "calculate", + "display", + "api" + ], "markdownDescription": "Cost calculation mode.", "type": "string" }, @@ -4241,7 +4476,10 @@ "order": { "default": "asc", "description": "Sort order.", - "enum": ["desc", "asc"], + "enum": [ + "desc", + "asc" + ], "markdownDescription": "Sort order.", "type": "string" }, @@ -4376,7 +4614,12 @@ "mode": { "default": "auto", "description": "Cost calculation mode.", - "enum": ["auto", "calculate", "display"], + "enum": [ + "auto", + "calculate", + "display", + "api" + ], "markdownDescription": "Cost calculation mode.", "type": "string" }, @@ -4407,7 +4650,10 @@ "order": { "default": "asc", "description": "Sort order.", - "enum": ["desc", "asc"], + "enum": [ + "desc", + "asc" + ], "markdownDescription": "Sort order.", "type": "string" }, @@ -4542,7 +4788,12 @@ "mode": { "default": "auto", "description": "Cost calculation mode.", - "enum": ["auto", "calculate", "display"], + "enum": [ + "auto", + "calculate", + "display", + "api" + ], "markdownDescription": "Cost calculation mode.", "type": "string" }, @@ -4573,7 +4824,10 @@ "order": { "default": "asc", "description": "Sort order.", - "enum": ["desc", "asc"], + "enum": [ + "desc", + "asc" + ], "markdownDescription": "Sort order.", "type": "string" }, @@ -4711,7 +4965,12 @@ "mode": { "default": "auto", "description": "Cost calculation mode.", - "enum": ["auto", "calculate", "display"], + "enum": [ + "auto", + "calculate", + "display", + "api" + ], "markdownDescription": "Cost calculation mode.", "type": "string" }, @@ -4742,7 +5001,10 @@ "order": { "default": "asc", "description": "Sort order.", - "enum": ["desc", "asc"], + "enum": [ + "desc", + "asc" + ], "markdownDescription": "Sort order.", "type": "string" }, @@ -4882,7 +5144,12 @@ "mode": { "default": "auto", "description": "Cost calculation mode.", - "enum": ["auto", "calculate", "display"], + "enum": [ + "auto", + "calculate", + "display", + "api" + ], "markdownDescription": "Cost calculation mode.", "type": "string" }, @@ -4913,7 +5180,10 @@ "order": { "default": "asc", "description": "Sort order.", - "enum": ["desc", "asc"], + "enum": [ + "desc", + "asc" + ], "markdownDescription": "Sort order.", "type": "string" }, @@ -5056,7 +5326,12 @@ "mode": { "default": "auto", "description": "Cost calculation mode.", - "enum": ["auto", "calculate", "display"], + "enum": [ + "auto", + "calculate", + "display", + "api" + ], "markdownDescription": "Cost calculation mode.", "type": "string" }, @@ -5087,7 +5362,10 @@ "order": { "default": "asc", "description": "Sort order.", - "enum": ["desc", "asc"], + "enum": [ + "desc", + "asc" + ], "markdownDescription": "Sort order.", "type": "string" }, @@ -5222,7 +5500,12 @@ "mode": { "default": "auto", "description": "Cost calculation mode.", - "enum": ["auto", "calculate", "display"], + "enum": [ + "auto", + "calculate", + "display", + "api" + ], "markdownDescription": "Cost calculation mode.", "type": "string" }, @@ -5253,7 +5536,10 @@ "order": { "default": "asc", "description": "Sort order.", - "enum": ["desc", "asc"], + "enum": [ + "desc", + "asc" + ], "markdownDescription": "Sort order.", "type": "string" }, @@ -5388,7 +5674,12 @@ "mode": { "default": "auto", "description": "Cost calculation mode.", - "enum": ["auto", "calculate", "display"], + "enum": [ + "auto", + "calculate", + "display", + "api" + ], "markdownDescription": "Cost calculation mode.", "type": "string" }, @@ -5419,7 +5710,10 @@ "order": { "default": "asc", "description": "Sort order.", - "enum": ["desc", "asc"], + "enum": [ + "desc", + "asc" + ], "markdownDescription": "Sort order.", "type": "string" }, @@ -5557,7 +5851,12 @@ "mode": { "default": "auto", "description": "Cost calculation mode.", - "enum": ["auto", "calculate", "display"], + "enum": [ + "auto", + "calculate", + "display", + "api" + ], "markdownDescription": "Cost calculation mode.", "type": "string" }, @@ -5588,7 +5887,10 @@ "order": { "default": "asc", "description": "Sort order.", - "enum": ["desc", "asc"], + "enum": [ + "desc", + "asc" + ], "markdownDescription": "Sort order.", "type": "string" }, @@ -5734,7 +6036,12 @@ "mode": { "default": "auto", "description": "Cost calculation mode.", - "enum": ["auto", "calculate", "display"], + "enum": [ + "auto", + "calculate", + "display", + "api" + ], "markdownDescription": "Cost calculation mode.", "type": "string" }, @@ -5765,7 +6072,10 @@ "order": { "default": "asc", "description": "Sort order.", - "enum": ["desc", "asc"], + "enum": [ + "desc", + "asc" + ], "markdownDescription": "Sort order.", "type": "string" }, @@ -5900,7 +6210,12 @@ "mode": { "default": "auto", "description": "Cost calculation mode.", - "enum": ["auto", "calculate", "display"], + "enum": [ + "auto", + "calculate", + "display", + "api" + ], "markdownDescription": "Cost calculation mode.", "type": "string" }, @@ -5931,7 +6246,10 @@ "order": { "default": "asc", "description": "Sort order.", - "enum": ["desc", "asc"], + "enum": [ + "desc", + "asc" + ], "markdownDescription": "Sort order.", "type": "string" }, @@ -6066,7 +6384,12 @@ "mode": { "default": "auto", "description": "Cost calculation mode.", - "enum": ["auto", "calculate", "display"], + "enum": [ + "auto", + "calculate", + "display", + "api" + ], "markdownDescription": "Cost calculation mode.", "type": "string" }, @@ -6097,7 +6420,10 @@ "order": { "default": "asc", "description": "Sort order.", - "enum": ["desc", "asc"], + "enum": [ + "desc", + "asc" + ], "markdownDescription": "Sort order.", "type": "string" }, @@ -6235,7 +6561,12 @@ "mode": { "default": "auto", "description": "Cost calculation mode.", - "enum": ["auto", "calculate", "display"], + "enum": [ + "auto", + "calculate", + "display", + "api" + ], "markdownDescription": "Cost calculation mode.", "type": "string" }, @@ -6266,7 +6597,10 @@ "order": { "default": "asc", "description": "Sort order.", - "enum": ["desc", "asc"], + "enum": [ + "desc", + "asc" + ], "markdownDescription": "Sort order.", "type": "string" }, @@ -6412,7 +6746,12 @@ "mode": { "default": "auto", "description": "Cost calculation mode.", - "enum": ["auto", "calculate", "display"], + "enum": [ + "auto", + "calculate", + "display", + "api" + ], "markdownDescription": "Cost calculation mode.", "type": "string" }, @@ -6443,7 +6782,10 @@ "order": { "default": "asc", "description": "Sort order.", - "enum": ["desc", "asc"], + "enum": [ + "desc", + "asc" + ], "markdownDescription": "Sort order.", "type": "string" }, @@ -6578,7 +6920,12 @@ "mode": { "default": "auto", "description": "Cost calculation mode.", - "enum": ["auto", "calculate", "display"], + "enum": [ + "auto", + "calculate", + "display", + "api" + ], "markdownDescription": "Cost calculation mode.", "type": "string" }, @@ -6609,7 +6956,10 @@ "order": { "default": "asc", "description": "Sort order.", - "enum": ["desc", "asc"], + "enum": [ + "desc", + "asc" + ], "markdownDescription": "Sort order.", "type": "string" }, @@ -6744,7 +7094,12 @@ "mode": { "default": "auto", "description": "Cost calculation mode.", - "enum": ["auto", "calculate", "display"], + "enum": [ + "auto", + "calculate", + "display", + "api" + ], "markdownDescription": "Cost calculation mode.", "type": "string" }, @@ -6775,7 +7130,10 @@ "order": { "default": "asc", "description": "Sort order.", - "enum": ["desc", "asc"], + "enum": [ + "desc", + "asc" + ], "markdownDescription": "Sort order.", "type": "string" }, @@ -6913,7 +7271,12 @@ "mode": { "default": "auto", "description": "Cost calculation mode.", - "enum": ["auto", "calculate", "display"], + "enum": [ + "auto", + "calculate", + "display", + "api" + ], "markdownDescription": "Cost calculation mode.", "type": "string" }, @@ -6944,7 +7307,10 @@ "order": { "default": "asc", "description": "Sort order.", - "enum": ["desc", "asc"], + "enum": [ + "desc", + "asc" + ], "markdownDescription": "Sort order.", "type": "string" }, @@ -7090,7 +7456,12 @@ "mode": { "default": "auto", "description": "Cost calculation mode.", - "enum": ["auto", "calculate", "display"], + "enum": [ + "auto", + "calculate", + "display", + "api" + ], "markdownDescription": "Cost calculation mode.", "type": "string" }, @@ -7121,7 +7492,10 @@ "order": { "default": "asc", "description": "Sort order.", - "enum": ["desc", "asc"], + "enum": [ + "desc", + "asc" + ], "markdownDescription": "Sort order.", "type": "string" }, @@ -7256,7 +7630,12 @@ "mode": { "default": "auto", "description": "Cost calculation mode.", - "enum": ["auto", "calculate", "display"], + "enum": [ + "auto", + "calculate", + "display", + "api" + ], "markdownDescription": "Cost calculation mode.", "type": "string" }, @@ -7287,7 +7666,10 @@ "order": { "default": "asc", "description": "Sort order.", - "enum": ["desc", "asc"], + "enum": [ + "desc", + "asc" + ], "markdownDescription": "Sort order.", "type": "string" }, @@ -7422,7 +7804,12 @@ "mode": { "default": "auto", "description": "Cost calculation mode.", - "enum": ["auto", "calculate", "display"], + "enum": [ + "auto", + "calculate", + "display", + "api" + ], "markdownDescription": "Cost calculation mode.", "type": "string" }, @@ -7453,7 +7840,10 @@ "order": { "default": "asc", "description": "Sort order.", - "enum": ["desc", "asc"], + "enum": [ + "desc", + "asc" + ], "markdownDescription": "Sort order.", "type": "string" }, @@ -7591,7 +7981,12 @@ "mode": { "default": "auto", "description": "Cost calculation mode.", - "enum": ["auto", "calculate", "display"], + "enum": [ + "auto", + "calculate", + "display", + "api" + ], "markdownDescription": "Cost calculation mode.", "type": "string" }, @@ -7622,7 +8017,10 @@ "order": { "default": "asc", "description": "Sort order.", - "enum": ["desc", "asc"], + "enum": [ + "desc", + "asc" + ], "markdownDescription": "Sort order.", "type": "string" }, @@ -7768,7 +8166,12 @@ "mode": { "default": "auto", "description": "Cost calculation mode.", - "enum": ["auto", "calculate", "display"], + "enum": [ + "auto", + "calculate", + "display", + "api" + ], "markdownDescription": "Cost calculation mode.", "type": "string" }, @@ -7799,7 +8202,10 @@ "order": { "default": "asc", "description": "Sort order.", - "enum": ["desc", "asc"], + "enum": [ + "desc", + "asc" + ], "markdownDescription": "Sort order.", "type": "string" }, @@ -7934,7 +8340,12 @@ "mode": { "default": "auto", "description": "Cost calculation mode.", - "enum": ["auto", "calculate", "display"], + "enum": [ + "auto", + "calculate", + "display", + "api" + ], "markdownDescription": "Cost calculation mode.", "type": "string" }, @@ -7965,7 +8376,10 @@ "order": { "default": "asc", "description": "Sort order.", - "enum": ["desc", "asc"], + "enum": [ + "desc", + "asc" + ], "markdownDescription": "Sort order.", "type": "string" }, @@ -8100,7 +8514,12 @@ "mode": { "default": "auto", "description": "Cost calculation mode.", - "enum": ["auto", "calculate", "display"], + "enum": [ + "auto", + "calculate", + "display", + "api" + ], "markdownDescription": "Cost calculation mode.", "type": "string" }, @@ -8131,7 +8550,10 @@ "order": { "default": "asc", "description": "Sort order.", - "enum": ["desc", "asc"], + "enum": [ + "desc", + "asc" + ], "markdownDescription": "Sort order.", "type": "string" }, @@ -8269,7 +8691,12 @@ "mode": { "default": "auto", "description": "Cost calculation mode.", - "enum": ["auto", "calculate", "display"], + "enum": [ + "auto", + "calculate", + "display", + "api" + ], "markdownDescription": "Cost calculation mode.", "type": "string" }, @@ -8300,7 +8727,10 @@ "order": { "default": "asc", "description": "Sort order.", - "enum": ["desc", "asc"], + "enum": [ + "desc", + "asc" + ], "markdownDescription": "Sort order.", "type": "string" }, @@ -8446,7 +8876,12 @@ "mode": { "default": "auto", "description": "Cost calculation mode.", - "enum": ["auto", "calculate", "display"], + "enum": [ + "auto", + "calculate", + "display", + "api" + ], "markdownDescription": "Cost calculation mode.", "type": "string" }, @@ -8477,7 +8912,10 @@ "order": { "default": "asc", "description": "Sort order.", - "enum": ["desc", "asc"], + "enum": [ + "desc", + "asc" + ], "markdownDescription": "Sort order.", "type": "string" }, @@ -8612,7 +9050,12 @@ "mode": { "default": "auto", "description": "Cost calculation mode.", - "enum": ["auto", "calculate", "display"], + "enum": [ + "auto", + "calculate", + "display", + "api" + ], "markdownDescription": "Cost calculation mode.", "type": "string" }, @@ -8643,7 +9086,10 @@ "order": { "default": "asc", "description": "Sort order.", - "enum": ["desc", "asc"], + "enum": [ + "desc", + "asc" + ], "markdownDescription": "Sort order.", "type": "string" }, @@ -8778,7 +9224,12 @@ "mode": { "default": "auto", "description": "Cost calculation mode.", - "enum": ["auto", "calculate", "display"], + "enum": [ + "auto", + "calculate", + "display", + "api" + ], "markdownDescription": "Cost calculation mode.", "type": "string" }, @@ -8809,7 +9260,10 @@ "order": { "default": "asc", "description": "Sort order.", - "enum": ["desc", "asc"], + "enum": [ + "desc", + "asc" + ], "markdownDescription": "Sort order.", "type": "string" }, @@ -8947,7 +9401,12 @@ "mode": { "default": "auto", "description": "Cost calculation mode.", - "enum": ["auto", "calculate", "display"], + "enum": [ + "auto", + "calculate", + "display", + "api" + ], "markdownDescription": "Cost calculation mode.", "type": "string" }, @@ -8978,7 +9437,10 @@ "order": { "default": "asc", "description": "Sort order.", - "enum": ["desc", "asc"], + "enum": [ + "desc", + "asc" + ], "markdownDescription": "Sort order.", "type": "string" }, @@ -9116,7 +9578,12 @@ }, "mode": { "description": "Cost calculation mode.", - "enum": ["auto", "calculate", "display"], + "enum": [ + "auto", + "calculate", + "display", + "api" + ], "markdownDescription": "Cost calculation mode.", "type": "string" }, @@ -9147,7 +9614,10 @@ }, "order": { "description": "Sort order.", - "enum": ["desc", "asc"], + "enum": [ + "desc", + "asc" + ], "markdownDescription": "Sort order.", "type": "string" }, @@ -9273,7 +9743,12 @@ }, "mode": { "description": "Cost calculation mode.", - "enum": ["auto", "calculate", "display"], + "enum": [ + "auto", + "calculate", + "display", + "api" + ], "markdownDescription": "Cost calculation mode.", "type": "string" }, @@ -9304,7 +9779,10 @@ }, "order": { "description": "Sort order.", - "enum": ["desc", "asc"], + "enum": [ + "desc", + "asc" + ], "markdownDescription": "Sort order.", "type": "string" }, @@ -9430,7 +9908,12 @@ }, "mode": { "description": "Cost calculation mode.", - "enum": ["auto", "calculate", "display"], + "enum": [ + "auto", + "calculate", + "display", + "api" + ], "markdownDescription": "Cost calculation mode.", "type": "string" }, @@ -9461,7 +9944,10 @@ }, "order": { "description": "Sort order.", - "enum": ["desc", "asc"], + "enum": [ + "desc", + "asc" + ], "markdownDescription": "Sort order.", "type": "string" }, @@ -9590,7 +10076,12 @@ }, "mode": { "description": "Cost calculation mode.", - "enum": ["auto", "calculate", "display"], + "enum": [ + "auto", + "calculate", + "display", + "api" + ], "markdownDescription": "Cost calculation mode.", "type": "string" }, @@ -9621,7 +10112,10 @@ }, "order": { "description": "Sort order.", - "enum": ["desc", "asc"], + "enum": [ + "desc", + "asc" + ], "markdownDescription": "Sort order.", "type": "string" }, @@ -9766,7 +10260,12 @@ "mode": { "default": "auto", "description": "Cost calculation mode.", - "enum": ["auto", "calculate", "display"], + "enum": [ + "auto", + "calculate", + "display", + "api" + ], "markdownDescription": "Cost calculation mode.", "type": "string" }, @@ -9797,7 +10296,10 @@ "order": { "default": "asc", "description": "Sort order.", - "enum": ["desc", "asc"], + "enum": [ + "desc", + "asc" + ], "markdownDescription": "Sort order.", "type": "string" }, @@ -9932,7 +10434,12 @@ "mode": { "default": "auto", "description": "Cost calculation mode.", - "enum": ["auto", "calculate", "display"], + "enum": [ + "auto", + "calculate", + "display", + "api" + ], "markdownDescription": "Cost calculation mode.", "type": "string" }, @@ -9963,7 +10470,10 @@ "order": { "default": "asc", "description": "Sort order.", - "enum": ["desc", "asc"], + "enum": [ + "desc", + "asc" + ], "markdownDescription": "Sort order.", "type": "string" }, @@ -10098,7 +10608,12 @@ "mode": { "default": "auto", "description": "Cost calculation mode.", - "enum": ["auto", "calculate", "display"], + "enum": [ + "auto", + "calculate", + "display", + "api" + ], "markdownDescription": "Cost calculation mode.", "type": "string" }, @@ -10129,7 +10644,10 @@ "order": { "default": "asc", "description": "Sort order.", - "enum": ["desc", "asc"], + "enum": [ + "desc", + "asc" + ], "markdownDescription": "Sort order.", "type": "string" }, @@ -10264,7 +10782,12 @@ "mode": { "default": "auto", "description": "Cost calculation mode.", - "enum": ["auto", "calculate", "display"], + "enum": [ + "auto", + "calculate", + "display", + "api" + ], "markdownDescription": "Cost calculation mode.", "type": "string" }, @@ -10295,7 +10818,10 @@ "order": { "default": "asc", "description": "Sort order.", - "enum": ["desc", "asc"], + "enum": [ + "desc", + "asc" + ], "markdownDescription": "Sort order.", "type": "string" }, @@ -10433,7 +10959,12 @@ "mode": { "default": "auto", "description": "Cost calculation mode.", - "enum": ["auto", "calculate", "display"], + "enum": [ + "auto", + "calculate", + "display", + "api" + ], "markdownDescription": "Cost calculation mode.", "type": "string" }, @@ -10464,7 +10995,10 @@ "order": { "default": "asc", "description": "Sort order.", - "enum": ["desc", "asc"], + "enum": [ + "desc", + "asc" + ], "markdownDescription": "Sort order.", "type": "string" }, @@ -10602,7 +11136,12 @@ }, "mode": { "description": "Cost calculation mode.", - "enum": ["auto", "calculate", "display"], + "enum": [ + "auto", + "calculate", + "display", + "api" + ], "markdownDescription": "Cost calculation mode.", "type": "string" }, @@ -10628,7 +11167,10 @@ }, "order": { "description": "Sort order.", - "enum": ["desc", "asc"], + "enum": [ + "desc", + "asc" + ], "markdownDescription": "Sort order.", "type": "string" }, @@ -10759,7 +11301,12 @@ }, "mode": { "description": "Cost calculation mode.", - "enum": ["auto", "calculate", "display"], + "enum": [ + "auto", + "calculate", + "display", + "api" + ], "markdownDescription": "Cost calculation mode.", "type": "string" }, @@ -10785,7 +11332,10 @@ }, "order": { "description": "Sort order.", - "enum": ["desc", "asc"], + "enum": [ + "desc", + "asc" + ], "markdownDescription": "Sort order.", "type": "string" }, @@ -10916,7 +11466,12 @@ }, "mode": { "description": "Cost calculation mode.", - "enum": ["auto", "calculate", "display"], + "enum": [ + "auto", + "calculate", + "display", + "api" + ], "markdownDescription": "Cost calculation mode.", "type": "string" }, @@ -10942,7 +11497,10 @@ }, "order": { "description": "Sort order.", - "enum": ["desc", "asc"], + "enum": [ + "desc", + "asc" + ], "markdownDescription": "Sort order.", "type": "string" }, @@ -11076,7 +11634,12 @@ }, "mode": { "description": "Cost calculation mode.", - "enum": ["auto", "calculate", "display"], + "enum": [ + "auto", + "calculate", + "display", + "api" + ], "markdownDescription": "Cost calculation mode.", "type": "string" }, @@ -11102,7 +11665,10 @@ }, "order": { "description": "Sort order.", - "enum": ["desc", "asc"], + "enum": [ + "desc", + "asc" + ], "markdownDescription": "Sort order.", "type": "string" }, @@ -11275,7 +11841,12 @@ "mode": { "default": "auto", "description": "Cost calculation mode.", - "enum": ["auto", "calculate", "display"], + "enum": [ + "auto", + "calculate", + "display", + "api" + ], "markdownDescription": "Cost calculation mode.", "type": "string" }, @@ -11306,7 +11877,10 @@ "order": { "default": "asc", "description": "Sort order.", - "enum": ["desc", "asc"], + "enum": [ + "desc", + "asc" + ], "markdownDescription": "Sort order.", "type": "string" }, @@ -11441,7 +12015,12 @@ "mode": { "default": "auto", "description": "Cost calculation mode.", - "enum": ["auto", "calculate", "display"], + "enum": [ + "auto", + "calculate", + "display", + "api" + ], "markdownDescription": "Cost calculation mode.", "type": "string" }, @@ -11472,7 +12051,10 @@ "order": { "default": "asc", "description": "Sort order.", - "enum": ["desc", "asc"], + "enum": [ + "desc", + "asc" + ], "markdownDescription": "Sort order.", "type": "string" }, @@ -11607,7 +12189,12 @@ "mode": { "default": "auto", "description": "Cost calculation mode.", - "enum": ["auto", "calculate", "display"], + "enum": [ + "auto", + "calculate", + "display", + "api" + ], "markdownDescription": "Cost calculation mode.", "type": "string" }, @@ -11638,7 +12225,10 @@ "order": { "default": "asc", "description": "Sort order.", - "enum": ["desc", "asc"], + "enum": [ + "desc", + "asc" + ], "markdownDescription": "Sort order.", "type": "string" }, @@ -11776,7 +12366,12 @@ "mode": { "default": "auto", "description": "Cost calculation mode.", - "enum": ["auto", "calculate", "display"], + "enum": [ + "auto", + "calculate", + "display", + "api" + ], "markdownDescription": "Cost calculation mode.", "type": "string" }, @@ -11807,7 +12402,10 @@ "order": { "default": "asc", "description": "Sort order.", - "enum": ["desc", "asc"], + "enum": [ + "desc", + "asc" + ], "markdownDescription": "Sort order.", "type": "string" }, diff --git a/docs/guide/cli-options.md b/docs/guide/cli-options.md index b41c4ca..6a73ce8 100644 --- a/docs/guide/cli-options.md +++ b/docs/guide/cli-options.md @@ -55,10 +55,15 @@ ccusage daily --mode auto # Calculate mode - always calculate from tokens ccusage daily --mode calculate +# api - alias for `calculate` (same behavior) +ccusage daily --mode api + # Display mode - only show pre-calculated costUSD ccusage daily --mode display ``` +See [Cost Modes](/guide/cost-modes) for a full breakdown of each mode. + ### Sort Order Control the ordering of results: diff --git a/docs/guide/configuration.md b/docs/guide/configuration.md index e41e27c..4abdb6a 100644 --- a/docs/guide/configuration.md +++ b/docs/guide/configuration.md @@ -55,10 +55,10 @@ export OPENCODE_DATA_DIR="$HOME/.local/share/opencode" export AMP_DATA_DIR="$HOME/.local/share/amp" export PI_AGENT_DIR="$HOME/.pi/agent/sessions" export KILO_DATA_DIR="$HOME/.local/share/kilo" -export COPILOT_OTEL_FILE_EXPORTER_PATH="$HOME/.copilot/otel/copilot-otel.jsonl" +export COPILOT_CONFIG_DIR="$HOME/.copilot" ``` -Use comma-separated directories when you want reports to combine multiple profiles or archives: +Use comma-separated directories when you want reports to combine multiple profiles or archives. `COPILOT_CONFIG_DIR` is the exception — it mirrors the Copilot CLI's own single-directory semantics and does not split on commas: ```bash export CODEX_HOME="$HOME/.codex,$HOME/.codex-work" diff --git a/docs/guide/copilot/index.md b/docs/guide/copilot/index.md index 4d8da3d..c82c7e6 100644 --- a/docs/guide/copilot/index.md +++ b/docs/guide/copilot/index.md @@ -1,8 +1,8 @@ # GitHub Copilot CLI Data Source (Beta) -> GitHub Copilot CLI support is experimental. The adapter reads local OpenTelemetry JSONL files only. +> GitHub Copilot CLI support is experimental. -ccusage can read GitHub Copilot CLI OpenTelemetry file exports as one of its supported local data sources. It uses the same reporting experience as the rest of ccusage: responsive tables, JSON output, LiteLLM-based pricing, cache token accounting, and all-source aggregation. +ccusage reads GitHub Copilot CLI usage from the per-session event stream the CLI writes by default (`~/.copilot/session-state//events.jsonl`). No configuration is required. Reporting uses the same experience as the rest of ccusage: responsive tables, JSON output, LiteLLM-based pricing, cache token accounting, and all-source aggregation. ## Focused Views @@ -24,23 +24,21 @@ pnpm dlx ccusage copilot --help ## Data Source -The CLI reads Copilot OpenTelemetry JSONL files from `~/.copilot/otel/*.jsonl` and also includes the explicit file pointed to by `COPILOT_OTEL_FILE_EXPORTER_PATH`. - -Enable these variables before starting or resuming a Copilot CLI session. Sessions that ran without OpenTelemetry file export enabled do not produce local JSONL usage data for ccusage to read. - -```bash -export COPILOT_OTEL_ENABLED=true -export COPILOT_OTEL_EXPORTER_TYPE=file -mkdir -p "$HOME/.copilot/otel" -export COPILOT_OTEL_FILE_EXPORTER_PATH="$HOME/.copilot/otel/copilot-otel-$(date +%Y%m%d-%H%M%S).jsonl" -``` +The Copilot CLI writes per-session events to `~/.copilot/session-state//events.jsonl` automatically during each CLI session — no configuration is required. ```text ~/.copilot/ -└── otel/ - └── *.jsonl +└── session-state/ + └── / + └── events.jsonl ``` +To override the base directory, set `COPILOT_CONFIG_DIR` to point elsewhere; ccusage will look for `session-state/` underneath it. + +### session-state event schema + +Each `events.jsonl` file contains a stream of JSON records. The adapter reads `session.shutdown` events only; their `data.modelMetrics` map carries per-model token totals (`usage.{inputTokens, outputTokens, cacheReadTokens, cacheWriteTokens, reasoningTokens}`) and request counts. A resumed Copilot session produces multiple shutdown events in the same file — each is a per-process snapshot, summed at report time. + ## Report Views | Focused view | Description | See also | @@ -51,28 +49,72 @@ export COPILOT_OTEL_FILE_EXPORTER_PATH="$HOME/.copilot/otel/copilot-otel-$(date These views support `--json` for structured output, `--compact` for narrow terminals, and `--offline` for cached pricing data. +## Pricing modes + +`ccusage copilot` supports the standard cost modes plus an `api` discoverability alias. For Copilot, the modes map to billing realities as follows: + +| Mode | What it shows for Copilot | +|---|---| +| `auto` (default) | **True bill, billing-field-aware**: AI Credits when `totalNanoAiu` is present (typically post-cutover sessions, CLI ≥ 1.0.40), premium-request × $0.04 when only `requests.cost` is present (typically pre-cutover sessions), token-priced when neither billing field is recorded | +| `display` | Source-precomputed only: AI Credits → premium-requests → `$0.00`. No token-priced fallback | +| `calculate` / `api` | Always LiteLLM token pricing — what the same usage would have cost via the underlying provider's API | + +Why billing-field-aware? GitHub Copilot switched billing models on June 1, 2026: pre-cutover sessions were billed as "premium requests" with per-model multipliers at $0.04 per overage request; post-cutover sessions bill as AI Credits at $0.01 per credit. The Copilot CLI records each session's own billing fields, so `auto` dispatches on which fields each session actually shipped (not on the recording date) — robust to backfills, future billing-channel additions, or sessions whose CLI version doesn't align with their date. + +```bash +# Default: billing-field-aware true bill (AI Credits when totalNanoAiu is present, premium-requests otherwise). +ccusage copilot daily + +# API-equivalent: what direct Anthropic/OpenAI/Google calls would have cost. +# Useful for justifying the Copilot subscription. +ccusage copilot daily --mode api + +# Source-precomputed only: walks AIU → premium-requests → $0. No fallback. +ccusage copilot daily --mode display +``` + +ccusage reads `totalNanoAiu` from each `session.shutdown` event and converts directly to USD (`credits × $0.01`). When a session ships only `requests.cost` (no AIU field), the loader falls back to `requests.cost × $0.04`. No LiteLLM pricing lookup happens in `display` mode, so newer Copilot model variants that aren't yet in the LiteLLM dataset still report correct cost. The `credits` field is exposed in `--json` output regardless of the selected mode, so you can always see the raw credit count. + +Credit-only `session.shutdown` rows (zero tokens, zero requests, non-null `totalNanoAiu`) are kept even when the default skip rule would otherwise discard them. Identical duplicate credit-only snapshots within the same session are collapsed via content-based deduplication. Free-tier models (sonnet, haiku with `requests.cost == 0`) genuinely cost $0 under the premium-request plan and are billed as such — not as their token-priced equivalent. + +See [Cost Modes](/guide/cost-modes) for the full mode reference. + ## What Gets Calculated -- **Token usage** - chat spans are preferred, with inference logs and agent-turn logs used as fallbacks. -- **Cache tokens** - cache read and cache creation token attributes are counted when present. -- **Reasoning tokens** - reasoning output tokens are included in total tokens and cost calculation. -- **Pricing** - costs are calculated from LiteLLM pricing data using the reported model name. +- **Token usage** — `inputTokens` in the session-state source schema already includes both cache reads and cache writes, so ccusage subtracts both to recover the "fresh" input bucket. +- **Cache tokens** — cache read and cache creation tokens are counted from the source's `cacheReadTokens` / `cacheWriteTokens` fields. +- **Reasoning tokens** — provider-dependent. For OpenAI (`gpt-*`) and Anthropic (`claude-*`) models reasoning is already inside `outputTokens` and is not double-counted. For Google (`gemini-*`) models reasoning is reported separately and is summed into the output cost bucket. +- **Credits** — when present, `totalNanoAiu` is divided by 10⁹ to get the AI Credit count (`1 credit = $0.01`). Always surfaced in JSON. Drives the cost figure under `auto` / `display` when present. +- **Pricing** — for `calculate` / `api` mode, costs are computed from LiteLLM pricing data using a normalized form of the model name. The raw name (e.g. `claude-opus-4.7-1m-internal`) is preserved in JSON, the table's `Models` column, and `modelsUsed`. ## Environment Variables -| Variable | Description | -| --------------------------------- | ---------------------------------------------------- | -| `COPILOT_OTEL_FILE_EXPORTER_PATH` | Explicit Copilot OpenTelemetry JSONL file to include | -| `LOG_LEVEL` | Adjust verbosity (0 silent ... 5 trace) | +| Variable | Description | +| -------------------- | -------------------------------------------------------------------------------------------- | +| `COPILOT_CONFIG_DIR` | Override the base Copilot directory (default: `~/.copilot`). `session-state/` is discovered underneath it. | +| `LOG_LEVEL` | Adjust verbosity (0 silent ... 5 trace) | ## Troubleshooting ::: details No Copilot usage data found -Ensure OpenTelemetry file export is enabled and the exporter path points to an existing `.jsonl` file, or place exported `.jsonl` files under `~/.copilot/otel/`. +The Copilot CLI writes per-session events to `~/.copilot/session-state//events.jsonl` automatically. If `ccusage copilot daily` still reports no data, verify that the directory exists and that at least one of the per-session subdirectories contains an `events.jsonl` with a `session.shutdown` event (resumed sessions only produce shutdown rows on graceful exit). -If you are using `copilot --resume`, set the OpenTelemetry environment variables before running the resume command. Earlier activity from sessions started without file export cannot be recovered by ccusage. +If you have configured `COPILOT_CONFIG_DIR`, make sure it points at the directory that contains `session-state/`. ::: ::: details Costs showing as $0.00 -If a model is not in LiteLLM's database, the cost will be $0.00. [Open an issue](https://github.com/ccusage/ccusage/issues/new) to request alias support. +There are two cases — most are genuine, only one is a problem. + +**Genuine $0.00** (no fix needed): + +- **Free-tier rows** under `--mode auto` / `--mode display` — sonnet/haiku entries shipped with `requests.cost == 0` legitimately cost $0 against your premium-request allotment. The source recorded zero; ccusage surfaces it faithfully. +- **Sessions without billing fields under `--mode display`** — rows that ship neither `totalNanoAiu` nor `requests.cost` resolve to $0 in display mode by design (display has no token-pricing fallback). + +**Unexpected $0.00** (file an issue): + +- A model is missing from LiteLLM's pricing dataset AND ccusage is on a token-priced path (`--mode calculate`, `--mode api`, or `--mode auto` falling back to token pricing because the session shipped neither `totalNanoAiu` nor `requests.cost`). In `--mode auto` / `--mode display`, rows with `totalNanoAiu` or `requests.cost` report cost directly from the source-precomputed values without consulting LiteLLM, so newer Copilot model variants that aren't yet in LiteLLM's database still bill correctly under those modes. If you hit this case on a token-priced path, [open an issue](https://github.com/ccusage/ccusage/issues/new) to request alias support. +::: + +::: details "ccusage no longer reads OpenTelemetry exports" warning +If you ran an older ccusage version with `COPILOT_OTEL_FILE_EXPORTER_PATH`, `COPILOT_OTEL_DEDUP`, or `COPILOT_PREFER_OTEL` set, you will now see a one-time stderr warning that these variables are ignored. ccusage now reads `~/.copilot/session-state//events.jsonl` directly — the OpenTelemetry export was a workaround for an older Copilot CLI that didn't expose its own usage data, and it is no longer needed. Unset the legacy variables (e.g. `unset COPILOT_OTEL_FILE_EXPORTER_PATH`) to silence the warning. Set `LOG_LEVEL=0` to silence it without unsetting the vars. ::: diff --git a/docs/guide/cost-modes.md b/docs/guide/cost-modes.md index 0c6073a..4e78e68 100644 --- a/docs/guide/cost-modes.md +++ b/docs/guide/cost-modes.md @@ -1,20 +1,20 @@ # Cost Modes -ccusage supports three different cost calculation modes to handle various scenarios and data sources. Understanding these modes helps you get the most accurate cost estimates for your usage analysis. +ccusage supports three cost calculation modes to handle various scenarios and data sources. Understanding these modes helps you get the most accurate cost estimates for your usage analysis. ## Overview Claude Code stores usage data in JSONL files with both token counts and pre-calculated cost information. ccusage can handle this data in different ways depending on your needs: - **`auto`** - Smart mode using the best available data -- **`calculate`** - Always calculate from token counts +- **`calculate`** (also aliased as **`api`**) - Always calculate from token counts (LiteLLM pricing) - **`display`** - Only show pre-calculated costs ## Mode Details ### auto (Default) -The `auto` mode intelligently chooses the best cost calculation method for each entry: +The `auto` mode intelligently chooses the best cost calculation method for each entry — it prefers whatever cost value the source already shipped, falling back to LiteLLM token pricing when none is available: ```bash ccusage daily --mode auto @@ -24,10 +24,18 @@ ccusage daily #### How it works: -1. **Pre-calculated costs available** → Uses Claude's `costUSD` values -2. **No pre-calculated costs** → Calculates from token counts using model pricing +1. **Source-precomputed cost available** → Uses it directly (Claude's `costUSD`, Copilot's AI Credits at `$0.01`/credit — converted from `totalNanoAiu / 10^9`, etc.) +2. **No pre-calculated cost** → Calculates from token counts using model pricing 3. **Mixed data** → Uses the best method for each entry +For Copilot specifically, `auto` is **billing-field-aware**: it picks the right billing model **per row** (each per-model entry inside a `session.shutdown` event) based on the billing fields the Copilot CLI recorded on that row — not on the session date. GitHub switched billing models on June 1, 2026, so different sessions ship different fields, but the loader dispatches on field presence (so a row backfilled to a different era still routes correctly): + +- **Rows with per-model `totalNanoAiu`** (typically CLI ≥ 1.0.40, post-cutover) → AI Credits × $0.01 — what GitHub actually bills against your AI Credit allotment. +- **Rows with per-model `requests.cost` but no AIU** (typically pre-cutover) → `requests.cost × $0.04` — what GitHub charged at the overage rate. Free-tier rows (`requests.cost == 0` for sonnet/haiku in your subscription) genuinely bill $0 under that model. +- **Rows without either billing field** (rare) → LiteLLM token pricing as best-effort fallback. + +If a `session.shutdown` event ALSO carries an event-level `data.totalNanoAiu` aggregate, ccusage emits a synthetic AI-Credit row carrying that aggregate **only** when no per-model row already carries a priced billing signal (per-model `totalNanoAiu > 0` OR `requests.cost > 0`). This prevents double-billing the same usage in AIU and premium-request currencies during the cutover transition — the per-model row is treated as authoritative when present, and the aggregate is surfaced only when it would otherwise be silently lost. + #### Best for: - ✅ **General usage** - Works well for most scenarios @@ -54,6 +62,12 @@ The `calculate` mode always computes costs from token counts using model pricing ```bash ccusage daily --mode calculate ccusage monthly --mode calculate --breakdown + +# `api` is an alias for `calculate` (same behavior — bills from +# LiteLLM token pricing). The shorter, intent-revealing name is useful +# for Copilot reports where you want to contrast the "API-equivalent" +# cost against `auto`'s "what Copilot actually billed" figure. +ccusage copilot daily --mode api ``` #### How it works: @@ -84,7 +98,7 @@ ccusage monthly --mode calculate --breakdown ### display -The `display` mode only shows pre-calculated costs from Claude Code: +The `display` mode only shows pre-calculated costs that the source data itself ships: ```bash ccusage daily --mode display @@ -93,15 +107,15 @@ ccusage session --mode display --json #### How it works: -1. **Uses only `costUSD` values** from Claude Code data -2. **Shows $0.00** for entries without pre-calculated costs +1. **Uses only the cost data present in the source** — Claude's `costUSD`, Copilot's `totalNanoAiu` (converted at `$0.01`/credit), or Copilot's `requests.cost × $0.04` for pre-AIU sessions +2. **Shows $0.00** for rows the source records as zero cost (older Claude data, Copilot free-tier rows with no billable credits or premium requests) 3. **No token-based calculations** performed -4. **Exact Claude billing data** when available +4. **Exact source billing data** when available #### Best for: -- ✅ **Official costs only** - Shows exactly what Claude calculated -- ✅ **Billing verification** - Comparing with actual Claude charges +- ✅ **Official costs only** - Shows exactly what the provider reported +- ✅ **Billing verification** - Comparing with actual provider charges - ✅ **Recent data** - Most accurate for newer usage entries - ✅ **Audit purposes** - Verifying pre-calculated costs diff --git a/docs/guide/environment-variables.md b/docs/guide/environment-variables.md index 206711e..d2674da 100644 --- a/docs/guide/environment-variables.md +++ b/docs/guide/environment-variables.md @@ -4,7 +4,7 @@ ccusage supports several environment variables for configuration and customizati ## Agent Data Directories -ccusage detects supported data source files from conventional locations by default. Set these variables when your data lives somewhere else. Directory variables can be one directory or a comma-separated list of directories; the Copilot variable points at one explicit JSONL export file: +ccusage detects supported data source files from conventional locations by default. Set these variables when your data lives somewhere else. Most directory variables accept a comma-separated list of directories; `COPILOT_CONFIG_DIR` is the exception — it mirrors the Copilot CLI's own single-directory semantics and reads `session-state/` underneath the one path you set: | Variable | Agent | Default | | --------------------------------- | ------------ | ---------------------------------- | @@ -21,7 +21,7 @@ ccusage detects supported data source files from conventional locations by defau | `KILO_DATA_DIR` | Kilo | `~/.local/share/kilo` | | `KIMI_DATA_DIR` | Kimi | `~/.kimi`, `~/.kimi-code` | | `QWEN_DATA_DIR` | Qwen | `~/.qwen` | -| `COPILOT_OTEL_FILE_EXPORTER_PATH` | Copilot CLI | Explicit `.jsonl` file | +| `COPILOT_CONFIG_DIR` | Copilot CLI | `~/.copilot` (base dir; reads `session-state//events.jsonl` underneath) | | `GEMINI_DATA_DIR` | Gemini CLI | `~/.gemini/tmp` | Example: @@ -34,17 +34,17 @@ export DROID_SESSIONS_DIR="/path/to/factory/sessions,/archive/factory/sessions" export CODEBUFF_DATA_DIR="/path/to/manicode,/archive/manicode" export HERMES_HOME="/path/to/hermes,/archive/hermes" export PI_AGENT_DIR="/path/to/pi/sessions,/archive/pi/sessions" -export GOOSE_PATH_ROOT="/path/to/goose,/archive/goose" +export GOOSE_PATH_ROOT="/path/to/goose" export OPENCLAW_DIR="/path/to/openclaw,/archive/openclaw" export KILO_DATA_DIR="/path/to/kilo,/archive/kilo" export KIMI_DATA_DIR="/path/to/kimi,/archive/kimi" export QWEN_DATA_DIR="/path/to/qwen,/archive/qwen" -export COPILOT_OTEL_FILE_EXPORTER_PATH="/path/to/copilot-otel.jsonl" +export COPILOT_CONFIG_DIR="/path/to/copilot" export GEMINI_DATA_DIR="/path/to/gemini/tmp,/archive/gemini/tmp" ccusage daily ``` -Empty entries, directories that do not exist, and missing explicit files are skipped. Duplicate paths are read once. +Empty entries, directories that do not exist, and missing explicit files are skipped. Duplicate paths are read once. `COPILOT_CONFIG_DIR` and `GOOSE_PATH_ROOT` are exceptions — they mirror each tool's own single-directory semantics and do not split on commas. ## CLAUDE_CONFIG_DIR diff --git a/docs/guide/getting-started.md b/docs/guide/getting-started.md index fdf101f..199d2a5 100644 --- a/docs/guide/getting-started.md +++ b/docs/guide/getting-started.md @@ -175,7 +175,7 @@ If ccusage shows no data, check: - Kimi: `${KIMI_DATA_DIR:-~/.kimi}` (also scans `~/.kimi-code`) - OpenClaw: `${OPENCLAW_DIR:-~/.openclaw}` (also scans `~/.clawdbot`, `~/.moltbot`, `~/.moldbot`) - Qwen: `${QWEN_DATA_DIR:-~/.qwen}` - - GitHub Copilot CLI: `~/.copilot/otel/*.jsonl` or `COPILOT_OTEL_FILE_EXPORTER_PATH` + - GitHub Copilot CLI: `${COPILOT_CONFIG_DIR:-~/.copilot}/session-state//events.jsonl` (written automatically by the CLI during each session) ### Custom Data Directory @@ -195,10 +195,10 @@ export OPENCLAW_DIR="/path/to/openclaw" export KILO_DATA_DIR="/path/to/kilo" export KIMI_DATA_DIR="/path/to/kimi" export QWEN_DATA_DIR="/path/to/qwen" -export COPILOT_OTEL_FILE_EXPORTER_PATH="/path/to/copilot-otel.jsonl" +export COPILOT_CONFIG_DIR="/path/to/copilot" ``` -Each source-specific path variable can also contain comma-separated directories: +Each source-specific path variable can also contain comma-separated directories — except `COPILOT_CONFIG_DIR` and `GOOSE_PATH_ROOT`, which both mirror their CLI's single-directory semantics: ```bash export CODEX_HOME="/path/to/codex,/archive/codex,/path/to/codex-exec-jsonl" @@ -208,7 +208,7 @@ export DROID_SESSIONS_DIR="/path/to/factory/sessions,/archive/factory/sessions" export CODEBUFF_DATA_DIR="/path/to/manicode,/archive/manicode" export HERMES_HOME="/path/to/hermes,/archive/hermes" export PI_AGENT_DIR="/path/to/pi/sessions,/archive/pi/sessions" -export GOOSE_PATH_ROOT="/path/to/goose,/archive/goose" +export GOOSE_PATH_ROOT="/path/to/goose" export OPENCLAW_DIR="/path/to/openclaw,/archive/openclaw" export KILO_DATA_DIR="/path/to/kilo,/archive/kilo" export KIMI_DATA_DIR="/path/to/kimi,/archive/kimi" diff --git a/docs/guide/index.md b/docs/guide/index.md index c0e969c..ef1748f 100644 --- a/docs/guide/index.md +++ b/docs/guide/index.md @@ -1,67 +1,13 @@ -# Introduction +# ccusage -![ccusage daily report showing token usage and costs by date](/screenshot.png) +A single CLI to read usage data from all your local AI coding agents and output unified reports. -**ccusage** is a local CLI for understanding coding (agent) CLI token usage and estimated costs across Claude Code, Codex, OpenCode, Amp, Droid, Codebuff, Hermes Agent, pi-agent, Goose, OpenClaw, Kilo, Kimi, Qwen, GitHub Copilot CLI, and Gemini CLI. +## What it does -The original **“cc”** came from **C**laude **C**ode usage and now also fits **C**odex **C**LI usage. As OpenCode, Amp, Droid, Codebuff, Hermes Agent, pi-agent, Goose, OpenClaw, Kilo, Kimi, Qwen, Gemini CLI, and other coding (agent) CLIs became part of the same workflow, ccusage expanded into a general name for local coding CLI usage analysis. - -## The Problem - -Modern coding (agent) CLI usage is split across several local data formats. That makes basic questions hard to answer: - -- How much am I actually using each coding CLI? -- Which conversations are the most expensive? -- What would I be paying on a pay-per-use plan? -- Which projects, sessions, or weeks are driving usage? - -## The Solution - -ccusage reads the local usage files that coding CLIs already generate and provides: - -- **All Sources by Default** - Claude Code, Codex, OpenCode, Amp, Droid, Codebuff, Hermes Agent, pi-agent, Goose, OpenClaw, Kilo, Kimi, Qwen, GitHub Copilot CLI, and Gemini CLI in one CLI -- **Usage Views** - Daily, weekly, monthly, and session-based breakdowns -- **Cost Analysis** - Estimated costs based on token usage and model pricing -- **Focused Data Source Views** - Start with all detected sources, then narrow the same usage views to one source when needed -- **Data Source Pages** - Source-specific setup and extra features live with each supported data source -- **Multiple Formats** - Beautiful tables or JSON for further analysis - -## How It Works - -1. **Coding CLIs generate local usage files** containing usage data -2. **ccusage reads these files** from your local machine -3. **Analyzes and aggregates** the data by date, session, or time blocks -4. **Calculates estimated costs** using model pricing information -5. **Presents results** in beautiful tables or JSON format - -## Key Features - -### 🚀 Direct Execution - -You can run ccusage without a global install using `bunx ccusage` (recommended), `pnpm dlx ccusage`, or `npx ccusage@latest`. - -### 📊 Usage Views - -- **All Sources (Default)** - Aggregates every detected supported source -- **Daily Usage** - Usage aggregated by calendar date -- **Weekly Usage** - Usage aggregated by week with configurable start day -- **Monthly Usage** - Monthly summaries with trends -- **Session Usage** - Per-conversation analysis - -### 💰 Cost Analysis - -- Estimated costs based on token counts and model pricing -- Support for different cost calculation modes -- Model-specific pricing across supported providers -- Cache token cost calculation - -### Data Source Pages - -Each data source page covers the details that only apply to that source, including custom directories, pricing notes, and source-specific commands. - -### 🔧 Flexible Configuration - -- **JSON Configuration Files** - Set defaults for all commands or customize per-command +- **Unified reports**: aggregate usage across multiple coding agents. +- **Per-agent reports**: inspect usage for a single agent with tailorable options. +- **Live pricing**: use public LiteLLM pricing or your own override file. +- **Offline mode**: cached pricing means the tool works without network access. - **IDE Support** - JSON Schema for autocomplete and validation - **Priority-based Settings** - CLI args > local config > user config > defaults - **Environment Variables** - Traditional configuration options @@ -72,26 +18,26 @@ Each data source page covers the details that only apply to that source, includi ccusage reads from local coding CLI data directories: -| Agent | ID | Default data location | -| ------------ | ---------- | ------------------------------------------------- | -| Claude Code | `claude` | `~/.config/claude/projects/`, `~/.claude/` | -| Codex | `codex` | `${CODEX_HOME:-~/.codex}` | -| OpenCode | `opencode` | `${OPENCODE_DATA_DIR:-~/.local/share/opencode}` | -| Amp | `amp` | `${AMP_DATA_DIR:-~/.local/share/amp}` | -| Droid | `droid` | `${DROID_SESSIONS_DIR:-~/.factory/sessions}` | -| Codebuff | `codebuff` | `${CODEBUFF_DATA_DIR:-~/.config/manicode}` | -| Hermes Agent | `hermes` | `${HERMES_HOME:-~/.hermes}/state.db` | -| pi-agent | `pi` | `${PI_AGENT_DIR:-~/.pi/agent/sessions}` | -| Goose | `goose` | Standard Goose data roots or `GOOSE_PATH_ROOT` | -| OpenClaw | `openclaw` | `${OPENCLAW_DIR:-~/.openclaw}` | -| Kilo | `kilo` | `${KILO_DATA_DIR:-~/.local/share/kilo}` | -| Kimi | `kimi` | `${KIMI_DATA_DIR:-~/.kimi}` (also `~/.kimi-code`) | -| Qwen | `qwen` | `${QWEN_DATA_DIR:-~/.qwen}` | -| Copilot CLI | `copilot` | `~/.copilot/otel/*.jsonl` | -| Gemini CLI | `gemini` | `${GEMINI_DATA_DIR:-~/.gemini/tmp}` | +| Agent | ID | Default data location | +| ------------ | ---------- | --------------------------------------------------------------------------- | +| Claude Code | `claude` | `~/.config/claude/projects/`, `~/.claude/` | +| Codex | `codex` | `${CODEX_HOME:-~/.codex}` | +| OpenCode | `opencode` | `${OPENCODE_DATA_DIR:-~/.local/share/opencode}` | +| Amp | `amp` | `${AMP_DATA_DIR:-~/.local/share/amp}` | +| Droid | `droid` | `${DROID_SESSIONS_DIR:-~/.factory/sessions}` | +| Codebuff | `codebuff` | `${CODEBUFF_DATA_DIR:-~/.config/manicode}` | +| Hermes Agent | `hermes` | `${HERMES_HOME:-~/.hermes}/state.db` | +| pi-agent | `pi` | `${PI_AGENT_DIR:-~/.pi/agent/sessions}` | +| Goose | `goose` | Standard Goose data roots or `GOOSE_PATH_ROOT` | +| OpenClaw | `openclaw` | `${OPENCLAW_DIR:-~/.openclaw}` | +| Kilo | `kilo` | `${KILO_DATA_DIR:-~/.local/share/kilo}` | +| Kimi | `kimi` | `${KIMI_DATA_DIR:-~/.kimi}` (also `~/.kimi-code`) | +| Qwen | `qwen` | `${QWEN_DATA_DIR:-~/.qwen}` | +| Copilot CLI | `copilot` | `${COPILOT_CONFIG_DIR:-~/.copilot}/session-state//events.jsonl` | +| Gemini CLI | `gemini` | `${GEMINI_DATA_DIR:-~/.gemini/tmp}` | The tool automatically detects available data and aggregates all supported coding CLIs by default. -Each source-specific environment variable can also contain comma-separated directories, which lets unified reports combine current profiles and archives. +Each source-specific environment variable can also contain comma-separated directories, which lets unified reports combine current profiles and archives. `COPILOT_CONFIG_DIR` is the exception — it mirrors the Copilot CLI's own single-directory semantics and does not split on commas. Some coding agents have been investigated but are not supported because their local files do not contain reliable token usage. See [Source Support Q&A](/guide/source-support-qa) for the current notes on Antigravity CLI, Grok CLI, and Devin CLI. @@ -106,50 +52,6 @@ ccusage monthly ccusage session ``` -Add a data source namespace when you want the same report focused on one source: - -```bash -ccusage claude daily -ccusage codex daily --speed fast -ccusage opencode weekly -ccusage amp session -ccusage droid daily -ccusage codebuff daily -ccusage hermes daily -ccusage pi monthly -ccusage goose daily -ccusage openclaw daily -ccusage kilo daily -ccusage kimi daily -ccusage qwen daily -ccusage copilot daily -ccusage gemini daily -``` - -Use `ccusage ` only when you want to narrow a report to one source. - -For Claude Code-specific setup and features, start from the [Claude Code data source](/guide/claude/) page. - -## Privacy & Security - -- **100% Local** - All analysis happens on your machine -- **No Data Transmission** - Your usage data never leaves your computer -- **Read-Only** - ccusage only reads files, never modifies them -- **Open Source** - Full transparency in how your data is processed - -## Limitations - -::: warning Important Limitations - -- **Local Files Only** - Only analyzes data from your current machine -- **Language Model Tokens** - API calls for tools like Web Search are not included -- **Estimate Accuracy** - Costs are estimates and may not reflect actual billing - ::: - -## Acknowledgments - -Thanks to [@milliondev](https://note.com/milliondev) for the [original concept and approach](https://note.com/milliondev/n/n1d018da2d769) to Claude Code usage analysis. - -## Getting Started +## CLI Options -Ready to analyze your coding (agent) CLI usage? Start with the [Getting Started Guide](/guide/getting-started). +See the [CLI options](/guide/cli-options) page for details on shared flags such as `--mode`, `--since`, `--until`, `--json`, and `--offline`. diff --git a/rust/crates/ccusage-cli/src/cli-commands.json b/rust/crates/ccusage-cli/src/cli-commands.json index c1a2a40..d4fd398 100644 --- a/rust/crates/ccusage-cli/src/cli-commands.json +++ b/rust/crates/ccusage-cli/src/cli-commands.json @@ -5,6 +5,7 @@ "claude_daily_options": ["shared_claude_options", "daily_options"], "claude_session_options": ["shared_claude_options", "session_options"], "claude_weekly_options": ["shared_claude_options", "weekly_options"], + "copilot_combined_options": ["agent_options", "copilot_options"], "openclaw_combined_options": ["agent_options", "openclaw_options"], "pi_combined_options": ["agent_options", "pi_options"] }, @@ -567,19 +568,19 @@ "path": ["copilot", "daily"], "description": "Show GitHub Copilot CLI usage grouped by date", "usage": "ccusage copilot daily ", - "options": "agent_options" + "options": "copilot_combined_options" }, { "path": ["copilot", "monthly"], "description": "Show GitHub Copilot CLI usage grouped by month", "usage": "ccusage copilot monthly ", - "options": "agent_options" + "options": "copilot_combined_options" }, { "path": ["copilot", "session"], "description": "Show GitHub Copilot CLI usage grouped by session", "usage": "ccusage copilot session ", - "options": "agent_options" + "options": "copilot_combined_options" }, { "path": ["gemini"], diff --git a/rust/crates/ccusage-cli/src/cli-help.json b/rust/crates/ccusage-cli/src/cli-help.json index 8e980fd..3aae919 100644 --- a/rust/crates/ccusage-cli/src/cli-help.json +++ b/rust/crates/ccusage-cli/src/cli-help.json @@ -121,6 +121,12 @@ "description": "Disable colored output. NO_COLOR=1 has the same effect.", "default": "auto" }, + { + "flags": "-m, --mode [mode]", + "description": "Cost calculation mode (api is an alias for calculate)", + "default": "auto", + "choices": ["auto", "calculate", "display", "api"] + }, { "flags": "--config ", "description": "Path to configuration file", @@ -238,6 +244,14 @@ "description": "Comma-separated project aliases (e.g., 'ccusage=Usage Tracker,myproject=My Project')" } ], + "copilot_options": [ + { + "flags": "-m, --mode [mode]", + "description": "Cost calculation mode (auto = billing-field-aware true bill; display = source precomputed only; calculate = LiteLLM token pricing; api is an alias for calculate)", + "default": "auto", + "choices": ["auto", "calculate", "display", "api"] + } + ], "pi_options": [ { "flags": "--pi-path ", @@ -272,9 +286,9 @@ }, { "flags": "-m, --mode [mode]", - "description": "Cost calculation mode", + "description": "Cost calculation mode (api is an alias for calculate)", "default": "auto", - "choices": ["auto", "calculate", "display"] + "choices": ["auto", "calculate", "display", "api"] }, { "flags": "-d, --debug", diff --git a/rust/crates/ccusage-cli/src/help_codegen.rs b/rust/crates/ccusage-cli/src/help_codegen.rs index c78c63d..3425234 100644 --- a/rust/crates/ccusage-cli/src/help_codegen.rs +++ b/rust/crates/ccusage-cli/src/help_codegen.rs @@ -366,13 +366,13 @@ mod tests { "flags": "--mode ", "description": "Cost calculation mode", "default": "auto", - "choices": ["auto", "calculate", "display"] + "choices": ["auto", "calculate", "display", "api"] } ]); let output = render_options(&options); assert!(output.contains("default: auto")); - assert!(output.contains("choices: auto | calculate | display")); + assert!(output.contains("choices: auto | calculate | display | api")); } } diff --git a/rust/crates/ccusage-cli/src/parser.rs b/rust/crates/ccusage-cli/src/parser.rs index 41c239a..3f1c96a 100644 --- a/rust/crates/ccusage-cli/src/parser.rs +++ b/rust/crates/ccusage-cli/src/parser.rs @@ -996,7 +996,12 @@ fn is_shared_flag(arg: &str) -> bool { fn parse_cost_mode(value: &str) -> Result { match value { "auto" => Ok(CostMode::Auto), - "calculate" => Ok(CostMode::Calculate), + // `api` is a discoverability alias for `calculate` — both bill + // from LiteLLM token pricing. The shorter, intent-revealing name + // is useful for Copilot reports where users want to contrast the + // "API-equivalent" cost against `auto`'s "what Copilot actually + // billed" figure. + "calculate" | "api" => Ok(CostMode::Calculate), "display" => Ok(CostMode::Display), _ => Err(format!("Invalid cost mode '{value}'")), } @@ -1105,4 +1110,28 @@ mod tests { Some(ControlArg::Version) ); } + + #[test] + fn parse_cost_mode_accepts_all_documented_values() { + assert_eq!(parse_cost_mode("auto"), Ok(CostMode::Auto)); + assert_eq!(parse_cost_mode("calculate"), Ok(CostMode::Calculate)); + assert_eq!(parse_cost_mode("display"), Ok(CostMode::Display)); + } + + #[test] + fn parse_cost_mode_api_aliases_calculate() { + // `api` is a discoverability alias for `calculate` — both bill + // from LiteLLM token pricing. Surfaces the api-equivalent intent + // in `--help` without expanding the `CostMode` enum. + assert_eq!(parse_cost_mode("api"), Ok(CostMode::Calculate)); + } + + #[test] + fn parse_cost_mode_rejects_unknown_values() { + assert!(parse_cost_mode("invalid").is_err()); + assert!(parse_cost_mode("").is_err()); + assert!(parse_cost_mode("API").is_err(), "case-sensitive"); + // Old pre-rename spelling is no longer accepted. + assert!(parse_cost_mode("api-equiv").is_err()); + } } diff --git a/rust/crates/ccusage-cli/src/snapshots/ccusage_cli__tests__root_help.snap b/rust/crates/ccusage-cli/src/snapshots/ccusage_cli__tests__root_help.snap index d269a64..da81f94 100644 --- a/rust/crates/ccusage-cli/src/snapshots/ccusage_cli__tests__root_help.snap +++ b/rust/crates/ccusage-cli/src/snapshots/ccusage_cli__tests__root_help.snap @@ -66,6 +66,7 @@ OPTIONS: --no-cost Hide cost information in table and JSON output (default: false) --color Enable colored output. FORCE_COLOR=1 has the same effect. (default: auto) --no-color Disable colored output. NO_COLOR=1 has the same effect. (default: auto) + -m, --mode [mode] Cost calculation mode (api is an alias for calculate) (default: auto, choices: auto | calculate | display | api) --config Path to configuration file (default: auto-discovery) -h, --help Display this help message -v, --version Display this version diff --git a/rust/crates/ccusage-test-support/src/lib.rs b/rust/crates/ccusage-test-support/src/lib.rs index 8cde912..92a1425 100644 --- a/rust/crates/ccusage-test-support/src/lib.rs +++ b/rust/crates/ccusage-test-support/src/lib.rs @@ -17,18 +17,26 @@ fn env_lock() -> MutexGuard<'static, ()> { } pub struct EnvVarGuard { - key: &'static str, - previous: Option, + previous: Vec<(&'static str, Option)>, _guard: MutexGuard<'static, ()>, } impl EnvVarGuard { pub fn set(key: &'static str, value: impl AsRef) -> Self { + Self::set_many(&[(key, Some(value.as_ref()))]) + } + + pub fn set_many(overrides: &[(&'static str, Option<&OsStr>)]) -> Self { let guard = env_lock(); - let previous = std::env::var_os(key); - unsafe { std::env::set_var(key, value) }; + let mut previous = Vec::with_capacity(overrides.len()); + for (key, value) in overrides { + previous.push((*key, std::env::var_os(key))); + match value { + Some(value) => unsafe { std::env::set_var(key, value) }, + None => unsafe { std::env::remove_var(key) }, + } + } Self { - key, previous, _guard: guard, } @@ -37,9 +45,11 @@ impl EnvVarGuard { impl Drop for EnvVarGuard { fn drop(&mut self) { - match self.previous.take() { - Some(value) => unsafe { std::env::set_var(self.key, value) }, - None => unsafe { std::env::remove_var(self.key) }, + for (key, value) in self.previous.drain(..).rev() { + match value { + Some(value) => unsafe { std::env::set_var(key, value) }, + None => unsafe { std::env::remove_var(key) }, + } } } } diff --git a/rust/crates/ccusage/src/adapter/all/loader.rs b/rust/crates/ccusage/src/adapter/all/loader.rs index 9b8c543..f9197e2 100644 --- a/rust/crates/ccusage/src/adapter/all/loader.rs +++ b/rust/crates/ccusage/src/adapter/all/loader.rs @@ -14,7 +14,7 @@ use crate::{ opencode, pi, qwen, }, cli::{AgentReportKind, CodexSpeed, NamedPiStore, SharedArgs, WeekDay}, - filter_loaded_entries_by_date, json_float, + filter_loaded_entries_by_date, }; use super::{ @@ -260,16 +260,7 @@ fn load_base_rows( index: 11, agent: BUILT_IN_AGENT_NAMES[11], progress_agent: crate::progress::UsageLoadAgent::Copilot, - load: Box::new(|| { - load_priced_summary_agent_rows( - "copilot", - load_kind, - &loader_shared, - pricing, - copilot::load_entries, - copilot::summarize_entries, - ) - }), + load: Box::new(|| load_copilot_rows(load_kind, &loader_shared, pricing)), }, AgentLoadSpec { index: 12, @@ -361,6 +352,18 @@ fn finish_rows(kind: AgentReportKind, mut rows: Vec, shared: &SharedArgs aggregated } +/// Post-process session-mode rows before rendering: clear `metadata_agents` +/// so the renderer's `build_row_metadata` does not inject an `"agents"` key +/// into per-session `--all --json` output. The clear is part of the +/// production `finish_rows` path; this helper is kept for tests that pin the +/// invariant directly. +#[cfg(test)] +pub(super) fn finalize_session_mode_rows(rows: &mut [AllRow]) { + for row in rows { + row.metadata_agents = None; + } +} + pub(super) fn load_agent_rows_parallel( specs: Vec>, progress: &mut crate::progress::UsageLoadProgress, @@ -672,6 +675,34 @@ fn load_qwen_rows(kind: AgentReportKind, shared: &SharedArgs) -> Result` +/// by `--since`/`--until` BEFORE the content-keyed dedup HashMap collapse +/// (required to keep in-range credit-only rows from being silently dropped +/// when they share `(session, model, naiu)` with an out-of-range row — see +/// `adapter/copilot/loader.rs::load_entries_inner` and the README section +/// "Date filter must run before dedup"). A side-effect is that +/// `!entries.is_empty()` after `load_entries` returns no longer reflects +/// on-disk presence — it reflects post-filter presence. We restore the +/// on-disk signal by OR-ing the lightweight `copilot::has_data()` sentinel +/// into `detected`, mirroring the established `qwen::has_data()` pattern. +/// This preserves the invariant that "copilot" appears in the `Detected:` +/// report header whenever any session-state file exists on disk, even when +/// the active date filter narrows the row set to empty. +fn load_copilot_rows( + kind: AgentReportKind, + shared: &SharedArgs, + pricing: &PricingMap, +) -> Result { + let mut entries = copilot::load_entries(shared, pricing)?; + let detected = !entries.is_empty() || copilot::has_data(); + filter_loaded_entries_by_date(&mut entries, shared); + let summaries = copilot::summarize_entries(&entries, kind)?; + Ok(AgentRows { + rows: summary_rows("copilot", summaries, false), + detected, + }) +} + fn summarize_entry_sessions(entries: &[LoadedEntry]) -> Result> { let mut groups = BTreeMap::<(String, String), SessionAccumulator>::new(); for entry in entries { @@ -724,9 +755,22 @@ fn summary_rows( .or(summary.session_id.as_ref())? .clone(); let total_tokens = summary.total_tokens(); - if total_tokens == 0 { + // Drop only fully-empty summaries (zero tokens AND zero cost + // AND zero/absent credits). The previous filter rejected any + // summary with `total_tokens == 0`, silently omitting + // post-cutover Copilot AI-Credit-only sessions. This relaxed + // predicate preserves the phantom-row guard while exposing + // genuine non-token billing — correct for any adapter that + // bills outside the token channel, not just Copilot. + // `total_cost == 0.0`: costs are non-negative; exact-zero + // only via all-zero terms (do not weaken to an epsilon). + if total_tokens == 0 + && summary.total_cost == 0.0 + && summary.credits.unwrap_or(0.0) == 0.0 + { return None; } + let credits = summary.credits; let metadata = summary_metadata(&summary, include_project_path); Some(AllRow { period, @@ -738,6 +782,7 @@ fn summary_rows( cache_read_tokens: summary.cache_read_tokens, total_tokens, total_cost: summary.total_cost, + credits, metadata, metadata_agents: Some(vec![agent]), agent_breakdowns: None, @@ -747,11 +792,18 @@ fn summary_rows( .collect() } +/// Builds the per-row `metadata` JSON object for session-mode rows. +/// +/// Note: `credits` is intentionally NOT included here — it's a first-class +/// field on `AllRow` (and `AllAccumulator` aggregates it). The renderer +/// (`report::row_json`) injects `credits` into the emitted `metadata` +/// object at serialization time, so aggregated `--all` rows surface +/// summed credits even though their `metadata` field is `None`. Keeping +/// `credits` out of the loader-side metadata map prevents a stale +/// per-source value from out-living the aggregator (which is what +/// originally dropped credits from `daily --all --json`). fn summary_metadata(summary: &UsageSummary, include_project_path: bool) -> Option { let mut metadata = serde_json::Map::new(); - if let Some(credits) = summary.credits { - metadata.insert("credits".to_string(), json_float(credits)); - } if summary.session_id.is_some() { if let Some(last_activity) = summary.last_activity.as_ref() { metadata.insert("lastActivity".to_string(), json!(last_activity)); @@ -802,6 +854,7 @@ pub(super) fn codex_group_row( cache_read_tokens: group.cached_input_tokens, total_tokens: group.total_tokens, total_cost: codex::calculate_group_cost(group, pricing, speed), + credits: None, metadata: Some(json!({ "lastActivity": group.last_activity, "reasoningOutputTokens": group.reasoning_output_tokens, @@ -1364,4 +1417,209 @@ mod tests { ] ); } + + #[test] + fn summary_rows_keeps_zero_token_summaries_when_cost_or_credits_present() { + // Regression: pre-fix `summary_rows` dropped any summary whose + // `total_tokens == 0`, silently omitting Copilot credit-only + // periods/sessions (zero tokens but positive `totalNanoAiu` → + // positive cost AND credits) from `ccusage daily --all` / + // `weekly --all` / `monthly --all` / `session --all` reports. The + // direct `ccusage copilot ...` reports surfaced them. The + // asymmetry was the bug. The relaxed predicate drops only + // fully-empty summaries (zero tokens AND zero cost AND + // zero/absent credits), restoring `--all` parity with the agent's + // own reports for any non-token billing channel. + + let credit_only_with_cost = UsageSummary { + total_cost: 1.54481, + credits: Some(154.481), + ..usage_summary("2026-05-15", 0) + }; + let credit_only_credits_no_cost = UsageSummary { + total_cost: 0.0, + credits: Some(2.5), + ..usage_summary("2026-05-16", 0) + }; + let cost_only_no_credits = UsageSummary { + total_cost: 0.04, + credits: None, + ..usage_summary("2026-05-17", 0) + }; + let fully_empty = usage_summary("2026-05-18", 0); + let token_only = usage_summary("2026-05-19", 100); + + let kept = summary_rows( + "copilot", + vec![ + credit_only_with_cost, + credit_only_credits_no_cost, + cost_only_no_credits, + fully_empty, + token_only, + ], + false, + ); + + let periods: Vec<&str> = kept.iter().map(|r| r.period.as_str()).collect(); + assert_eq!( + periods, + vec![ + "2026-05-15", // credit-only with cost + credits — kept + "2026-05-16", // credit-only with credits, $0 cost — kept (Display mode) + "2026-05-17", // cost > 0 with no credits — kept (codebuff-shape forward-compat) + "2026-05-19", // token-bearing — kept (pre-existing behavior preserved) + ], + "fully-empty summary (2026-05-18) must still be dropped; \ + any summary with non-zero tokens, cost, or credits must survive", + ); + } + + #[test] + fn summary_rows_treats_zero_credits_same_as_absent_credits() { + // Belt-and-suspenders: `Some(0.0)` credits + zero tokens + zero + // cost still drops the summary. Without this, a future bug that + // populates `credits = Some(0.0)` (instead of `None`) on a + // phantom row would re-surface the all-zero summary in `--all`. + + let zero_credits = UsageSummary { + total_cost: 0.0, + credits: Some(0.0), + ..usage_summary("2026-05-20", 0) + }; + + let kept = summary_rows("copilot", vec![zero_credits], false); + + assert!( + kept.is_empty(), + "zero-tokens + zero-cost + Some(0.0) credits must be treated \ + as fully empty and dropped", + ); + } + + #[test] + fn summary_rows_relaxed_filter_applies_uniformly_across_non_copilot_agents() { + // Cross-agent behavior change pinned: the relaxation of + // `summary_rows` (from `total_tokens == 0 → drop` to + // `total_tokens == 0 && total_cost == 0.0 && credits.unwrap_or(0.0) == 0.0 + // → drop`) is INTENTIONALLY agent-agnostic. Pre-fix, any + // non-Copilot adapter producing a zero-token + positive-cost + // summary had its row silently dropped from `ccusage daily --all` + // / `--all --json` totals. + // + // Run the same shape (zero tokens + positive cost + no credits) + // through three labels — claude and hermes (genuine producers + // of the shape today) and `future-cost-only-agent` (a synthetic + // label that emphasizes filter agent-agnosticism beyond any + // currently-shipping adapter) — and assert all three survive. + // Companion loop asserts the still-fully-empty row drops + // uniformly across the same labels (phantom-row guard fires + // cross-agent). + + let agents: &[&'static str] = &["claude", "hermes", "future-cost-only-agent"]; + for agent in agents { + let cost_only = UsageSummary { + total_cost: 0.0234, + credits: None, + ..usage_summary("2026-05-20", 0) + }; + let kept = summary_rows(agent, vec![cost_only], false); + assert_eq!( + kept.len(), + 1, + "agent={agent}: zero-token + positive-cost row must \ + survive `summary_rows` (relaxed filter applies \ + cross-agent, not just to Copilot)", + ); + assert_eq!(kept[0].agent, *agent); + assert!((kept[0].total_cost - 0.0234).abs() < 1e-9); + assert_eq!(kept[0].credits, None); + } + + // Companion: still-fully-empty row drops regardless of agent. + for agent in agents { + let fully_empty = usage_summary("2026-05-21", 0); + let kept = summary_rows(agent, vec![fully_empty], false); + assert!( + kept.is_empty(), + "agent={agent}: fully-empty row (zero tokens + zero cost \ + + no credits) must still be dropped — the phantom-row \ + guard fires uniformly cross-agent", + ); + } + } + + #[test] + fn load_copilot_rows_keeps_copilot_in_detected_when_date_filter_excludes_all_data() { + let fixture = ccusage_test_support::Fixture::new(); + let session_uuid = "session-detected-when-filtered-out"; + let event = serde_json::json!({ + "type": "session.shutdown", + "id": "evt-credit-only", + "timestamp": "2026-05-15T10:00:00.000Z", + "data": {"modelMetrics": { + "claude-opus-4.7-1m-internal": { + "usage": { + "inputTokens": 0u64, + "outputTokens": 0u64, + "cacheReadTokens": 0u64, + "cacheWriteTokens": 0u64, + "reasoningTokens": 0u64 + }, + "requests": {"count": 0u64, "cost": 0}, + "totalNanoAiu": 154_481_000_000u64 + } + }} + }); + let _ = fixture.write_file( + format!("session-state/{session_uuid}/events.jsonl"), + format!("{event}\n"), + ); + let _env = + ccusage_test_support::EnvVarGuard::set(copilot::COPILOT_CONFIG_DIR_ENV, fixture.root()); + + let shared = SharedArgs { + json: true, + offline: true, + mode: crate::cli::CostMode::Auto, + since: Some("21000101".to_string()), + timezone: Some("UTC".to_string()), + ..SharedArgs::default() + }; + let pricing = PricingMap::default(); + let agent_rows = load_copilot_rows(AgentReportKind::Daily, &shared, &pricing).unwrap(); + + assert!( + agent_rows.rows.is_empty(), + "the date filter should have excluded all rows; got {} rows", + agent_rows.rows.len(), + ); + assert!( + agent_rows.detected, + "copilot should remain detected after date filtering", + ); + } + + #[test] + fn load_copilot_rows_reports_not_detected_when_no_session_state_files_exist() { + let fixture = ccusage_test_support::Fixture::new(); + let _env = + ccusage_test_support::EnvVarGuard::set(copilot::COPILOT_CONFIG_DIR_ENV, fixture.root()); + + let shared = SharedArgs { + json: true, + offline: true, + mode: crate::cli::CostMode::Auto, + ..SharedArgs::default() + }; + let pricing = PricingMap::default(); + let agent_rows = load_copilot_rows(AgentReportKind::Daily, &shared, &pricing).unwrap(); + + assert!(agent_rows.rows.is_empty()); + assert!( + !agent_rows.detected, + "with no Copilot data on disk, `detected` must be false so \ + `Detected:` does not falsely list copilot", + ); + } } diff --git a/rust/crates/ccusage/src/adapter/all/mod.rs b/rust/crates/ccusage/src/adapter/all/mod.rs index 6ac42ef..b51b877 100644 --- a/rust/crates/ccusage/src/adapter/all/mod.rs +++ b/rust/crates/ccusage/src/adapter/all/mod.rs @@ -63,7 +63,10 @@ fn requested_sections( } #[cfg(test)] -use loader::{aggregate_rows, codex_group_row, load_agent_rows_parallel, load_rows, load_sections}; +use loader::{ + aggregate_rows, codex_group_row, finalize_session_mode_rows, load_agent_rows_parallel, + load_rows, load_sections, +}; #[cfg(test)] use report::{ all_report_title, all_table_columns, all_table_row, report_json, report_json_with_agents, diff --git a/rust/crates/ccusage/src/adapter/all/report.rs b/rust/crates/ccusage/src/adapter/all/report.rs index 49a6b57..da1df12 100644 --- a/rust/crates/ccusage/src/adapter/all/report.rs +++ b/rust/crates/ccusage/src/adapter/all/report.rs @@ -134,15 +134,10 @@ fn row_json(row: &AllRow, include_agents: bool) -> Value { if let Some(obj) = value.as_object_mut() { obj.insert("period".to_string(), json!(row.period)); } - if let (Some(obj), Some(agents)) = (value.as_object_mut(), row.metadata_agents.as_ref()) { - obj.insert( - "metadata".to_string(), - row.metadata - .clone() - .unwrap_or_else(|| json!({ "agents": agents })), - ); - } else if let (Some(obj), Some(metadata)) = (value.as_object_mut(), row.metadata.as_ref()) { - obj.insert("metadata".to_string(), metadata.clone()); + if let Some(metadata) = build_row_metadata(row) + && let Some(obj) = value.as_object_mut() + { + obj.insert("metadata".to_string(), metadata); } if include_agents && let (Some(obj), Some(agent_breakdowns)) = @@ -156,29 +151,40 @@ fn row_json(row: &AllRow, include_agents: bool) -> Value { value } -fn agent_json(row: &AllRow) -> Value { - json!({ - "agent": row.agent, - "modelsUsed": row.models_used, - "inputTokens": row.input_tokens, - "outputTokens": row.output_tokens, - "cacheCreationTokens": row.cache_creation_tokens, - "cacheReadTokens": row.cache_read_tokens, - "totalTokens": row.total_tokens, - "totalCost": json_float(row.total_cost), - "modelBreakdowns": row.model_breakdowns, - }) +fn build_row_metadata(row: &AllRow) -> Option { + let mut map = row + .metadata + .as_ref() + .and_then(Value::as_object) + .cloned() + .unwrap_or_default(); + if let Some(agents) = row.metadata_agents.as_ref() + && !map.contains_key("agents") + { + map.insert("agents".to_string(), json!(agents)); + } + if let Some(credits) = row.credits { + map.insert("credits".to_string(), json!(credits)); + } + (!map.is_empty()).then_some(Value::Object(map)) } fn totals_json(rows: &[AllRow]) -> Value { - json!({ + let mut totals = json!({ "inputTokens": rows.iter().map(|row| row.input_tokens).sum::(), "outputTokens": rows.iter().map(|row| row.output_tokens).sum::(), "cacheCreationTokens": rows.iter().map(|row| row.cache_creation_tokens).sum::(), "cacheReadTokens": rows.iter().map(|row| row.cache_read_tokens).sum::(), "totalTokens": rows.iter().map(|row| row.total_tokens).sum::(), "totalCost": json_float(rows.iter().map(|row| row.total_cost).sum::()), - }) + }); + let total_credits = rows.iter().filter_map(|row| row.credits).sum::(); + if total_credits > 0.0 + && let Some(obj) = totals.as_object_mut() + { + obj.insert("credits".to_string(), json!(total_credits)); + } + totals } fn rows_key(kind: AgentReportKind) -> &'static str { @@ -190,6 +196,20 @@ fn rows_key(kind: AgentReportKind) -> &'static str { } } +fn agent_json(row: &AllRow) -> Value { + json!({ + "agent": row.agent, + "modelsUsed": row.models_used, + "inputTokens": row.input_tokens, + "outputTokens": row.output_tokens, + "cacheCreationTokens": row.cache_creation_tokens, + "cacheReadTokens": row.cache_read_tokens, + "totalTokens": row.total_tokens, + "totalCost": json_float(row.total_cost), + "modelBreakdowns": row.model_breakdowns, + }) +} + pub(super) fn print_table( rows: &[AllRow], kind: AgentReportKind, diff --git a/rust/crates/ccusage/src/adapter/all/tests.rs b/rust/crates/ccusage/src/adapter/all/tests.rs index 193479a..fb86b0f 100644 --- a/rust/crates/ccusage/src/adapter/all/tests.rs +++ b/rust/crates/ccusage/src/adapter/all/tests.rs @@ -30,6 +30,7 @@ fn test_agent_rows(agent: &'static str) -> AgentRows { cache_read_tokens: 0, total_tokens: 1, total_cost: 0.0, + credits: None, metadata: None, metadata_agents: Some(vec![agent]), agent_breakdowns: None, @@ -91,6 +92,7 @@ fn aggregates_daily_agent_rows_by_period() { cache_read_tokens: 10, total_tokens: 120, total_cost: 0.01, + credits: None, metadata: None, metadata_agents: Some(vec!["codex"]), agent_breakdowns: None, @@ -106,6 +108,7 @@ fn aggregates_daily_agent_rows_by_period() { cache_read_tokens: 3, total_tokens: 83, total_cost: 0.02, + credits: None, metadata: None, metadata_agents: Some(vec!["claude"]), agent_breakdowns: None, @@ -148,6 +151,7 @@ fn merges_same_agent_daily_rows_into_one_monthly_breakdown() { cache_read_tokens: 2, total_tokens: 18, total_cost: 0.01, + credits: None, metadata: None, metadata_agents: Some(vec!["claude"]), agent_breakdowns: None, @@ -171,6 +175,7 @@ fn merges_same_agent_daily_rows_into_one_monthly_breakdown() { cache_read_tokens: 4, total_tokens: 36, total_cost: 0.05, + credits: None, metadata: None, metadata_agents: Some(vec!["claude"]), agent_breakdowns: None, @@ -194,6 +199,7 @@ fn merges_same_agent_daily_rows_into_one_monthly_breakdown() { cache_read_tokens: 6, total_tokens: 51, total_cost: 0.02, + credits: None, metadata: None, metadata_agents: Some(vec!["codex"]), agent_breakdowns: None, @@ -268,6 +274,7 @@ fn renders_all_report_json_with_period_and_agent_metadata() { cache_read_tokens: 10, total_tokens: 130, total_cost: 0.01, + credits: None, metadata: None, metadata_agents: Some(vec!["codex"]), agent_breakdowns: None, @@ -294,6 +301,7 @@ fn renders_by_agent_json_breakdowns_when_requested() { cache_read_tokens: 13, total_tokens: 203, total_cost: 0.03, + credits: None, metadata: None, metadata_agents: Some(vec!["claude", "codex"]), agent_breakdowns: Some(vec![ @@ -307,6 +315,7 @@ fn renders_by_agent_json_breakdowns_when_requested() { cache_read_tokens: 3, total_tokens: 83, total_cost: 0.02, + credits: None, metadata: None, metadata_agents: Some(vec!["claude"]), agent_breakdowns: None, @@ -330,6 +339,7 @@ fn renders_by_agent_json_breakdowns_when_requested() { cache_read_tokens: 10, total_tokens: 120, total_cost: 0.01, + credits: None, metadata: None, metadata_agents: Some(vec!["codex"]), agent_breakdowns: None, @@ -393,6 +403,7 @@ fn omits_by_agent_json_breakdowns_by_default() { cache_read_tokens: 10, total_tokens: 120, total_cost: 0.01, + credits: None, metadata: None, metadata_agents: Some(vec!["codex"]), agent_breakdowns: None, @@ -418,6 +429,7 @@ fn renders_multi_section_json_with_command_totals() { cache_read_tokens: 10, total_tokens: 120, total_cost: 0.01, + credits: None, metadata: None, metadata_agents: Some(vec!["codex"]), agent_breakdowns: None, @@ -434,6 +446,7 @@ fn renders_multi_section_json_with_command_totals() { cache_read_tokens: 10, total_tokens: 120, total_cost: 0.01, + credits: None, metadata: Some(json!({ "lastActivity": "2026-01-02T00:00:00.000Z" })), metadata_agents: None, agent_breakdowns: None, @@ -737,6 +750,7 @@ fn aggregates_model_breakdowns_across_agents() { cache_read_tokens: 2, total_tokens: 17, total_cost: 0.03, + credits: None, metadata: None, metadata_agents: Some(vec!["codex"]), agent_breakdowns: None, @@ -760,6 +774,7 @@ fn aggregates_model_breakdowns_across_agents() { cache_read_tokens: 4, total_tokens: 57, total_cost: 0.07, + credits: None, metadata: None, metadata_agents: Some(vec!["claude"]), agent_breakdowns: None, @@ -817,6 +832,7 @@ fn displays_total_tokens_with_cache_tokens_like_typescript_table() { cache_read_tokens: 10, total_tokens: 120, total_cost: 0.01, + credits: None, metadata: None, metadata_agents: Some(vec!["codex"]), agent_breakdowns: None, @@ -840,6 +856,7 @@ fn report_title_uses_detected_agents_even_when_filtered_rows_are_sparse() { cache_read_tokens: 10, total_tokens: 120, total_cost: 0.01, + credits: None, metadata: None, metadata_agents: Some(vec!["codex"]), agent_breakdowns: None, @@ -870,6 +887,7 @@ fn all_table_rows_match_main_agent_breakdown_display() { cache_read_tokens: 10, total_tokens: 130, total_cost: 0.01, + credits: None, metadata: None, metadata_agents: Some(vec!["codex"]), agent_breakdowns: Some(vec![AllRow { @@ -882,6 +900,7 @@ fn all_table_rows_match_main_agent_breakdown_display() { cache_read_tokens: 10, total_tokens: 130, total_cost: 0.01, + credits: None, metadata: None, metadata_agents: Some(vec!["codex"]), agent_breakdowns: None, @@ -917,6 +936,7 @@ fn all_report_title_lists_detected_agents() { cache_read_tokens: 0, total_tokens: 0, total_cost: 0.0, + credits: None, metadata: None, metadata_agents: Some(vec!["claude", "codex"]), agent_breakdowns: None, @@ -970,3 +990,431 @@ fn full_table_columns_include_cache_and_total_token_metrics() { ); assert_eq!(headers.len(), aligns.len()); } + +#[test] +fn all_aggregator_sums_credits_across_agents_and_surfaces_them_in_json() { + let copilot_day = AllRow { + period: "2026-05-15".to_string(), + agent: "copilot", + models_used: vec!["claude-opus-4.7-1m-internal".to_string()], + input_tokens: 0, + output_tokens: 0, + cache_creation_tokens: 0, + cache_read_tokens: 0, + total_tokens: 0, + total_cost: 1.54481, + credits: Some(154.481), + metadata: None, + metadata_agents: Some(vec!["copilot"]), + agent_breakdowns: None, + model_breakdowns: Vec::new(), + }; + let codex_day = AllRow { + period: "2026-05-15".to_string(), + agent: "codex", + models_used: vec!["gpt-5".to_string()], + input_tokens: 100, + output_tokens: 20, + cache_creation_tokens: 0, + cache_read_tokens: 10, + total_tokens: 130, + total_cost: 0.01, + credits: None, // codex doesn't report credits + metadata: None, + metadata_agents: Some(vec!["codex"]), + agent_breakdowns: None, + model_breakdowns: Vec::new(), + }; + + let aggregated = aggregate_rows(vec![copilot_day, codex_day], AgentReportKind::Daily); + assert_eq!(aggregated.len(), 1); + assert_eq!(aggregated[0].agent, "all"); + assert_eq!( + aggregated[0].credits, + Some(154.481), + "aggregated `all` row must carry the summed credits across \ + contributing agents; codex's `None` must not zero it" + ); + + let report = report_json(&aggregated, AgentReportKind::Daily); + let top_metadata = &report["daily"][0]["metadata"]; + assert_eq!( + top_metadata["agents"], + serde_json::json!(["codex", "copilot"]), + "top-level `agents` metadata must still list both contributors", + ); + assert!( + top_metadata["credits"].is_number(), + "top-level `metadata.credits` must surface the aggregated credits; \ + got {top_metadata:?}", + ); + assert!( + (top_metadata["credits"].as_f64().unwrap() - 154.481).abs() < 1e-9, + "expected metadata.credits == 154.481, got {}", + top_metadata["credits"], + ); + + let totals = &report["totals"]; + assert!( + totals["credits"].is_number(), + "totals must include `credits` whenever any row reports credits \ + (matching the direct-agent `output.rs::totals_json` key); \ + got {totals:?}", + ); + assert!( + (totals["credits"].as_f64().unwrap() - 154.481).abs() < 1e-9, + "expected totals.credits == 154.481, got {}", + totals["credits"], + ); +} + +#[test] +fn all_aggregator_merges_same_agent_credits_across_multiple_days() { + // Same-agent merge path: `merge_agent_breakdown` must sum credits + // across days of the SAME agent. Pre-fix this discarded the + // metadata-side credits entirely (`merge_agent_breakdown` never + // touched `metadata`), so weekly/monthly aggregation of a credit- + // bearing agent (e.g. Copilot) showed only the FIRST day's credits + // on its breakdown — even though tokens and cost summed correctly. + + let day1 = AllRow { + period: "2026-05-15".to_string(), + agent: "copilot", + models_used: vec!["claude-opus-4.7-1m-internal".to_string()], + input_tokens: 0, + output_tokens: 0, + cache_creation_tokens: 0, + cache_read_tokens: 0, + total_tokens: 0, + total_cost: 1.0, + credits: Some(100.0), + metadata: None, + metadata_agents: Some(vec!["copilot"]), + agent_breakdowns: None, + model_breakdowns: Vec::new(), + }; + let day2 = AllRow { + period: "2026-05-16".to_string(), + agent: "copilot", + models_used: vec!["claude-opus-4.7-1m-internal".to_string()], + input_tokens: 0, + output_tokens: 0, + cache_creation_tokens: 0, + cache_read_tokens: 0, + total_tokens: 0, + total_cost: 0.5, + credits: Some(50.0), + metadata: None, + metadata_agents: Some(vec!["copilot"]), + agent_breakdowns: None, + model_breakdowns: Vec::new(), + }; + + // Monthly aggregation collapses both days into one period. + let aggregated = aggregate_rows(vec![day1, day2], AgentReportKind::Monthly); + assert_eq!(aggregated.len(), 1); + assert_eq!( + aggregated[0].credits, + Some(150.0), + "monthly `all` row must sum credits across days for the same agent" + ); + let breakdowns = aggregated[0].agent_breakdowns.as_ref().unwrap(); + assert_eq!(breakdowns.len(), 1); + assert_eq!(breakdowns[0].agent, "copilot"); + assert_eq!( + breakdowns[0].credits, + Some(150.0), + "per-agent breakdown must also sum credits across same-agent days \ + (pre-fix only the first day's credits survived `merge_agent_breakdown`)" + ); +} + +#[test] +fn totals_json_omits_credits_when_no_row_reports_credits() { + // Backward-compatibility: agents that have never reported credits + // (Claude, Codex, Amp, …) must continue to see the same totals + // JSON shape they always have — no spurious `credits: 0` field. + // The gate fires only when the SUM is positive, matching the + // direct per-agent renderer (`output.rs::totals_json`, + // `if credits > 0.0`). This keeps the totals shape byte-identical + // across direct and `--all` reports for ALL inputs — including + // `Some(0.0)` (a Copilot post-cutover day whose `totalNanoAiu == 0`, + // pinned separately by + // `totals_json_omits_credits_when_all_credits_sum_to_zero`). + + let credit_free = vec![AllRow { + period: "2026-05-15".to_string(), + agent: "all", + models_used: vec!["gpt-5".to_string()], + input_tokens: 100, + output_tokens: 20, + cache_creation_tokens: 0, + cache_read_tokens: 10, + total_tokens: 130, + total_cost: 0.01, + credits: None, + metadata: None, + metadata_agents: Some(vec!["codex"]), + agent_breakdowns: None, + model_breakdowns: Vec::new(), + }]; + + let report = report_json(&credit_free, AgentReportKind::Daily); + assert!( + report["totals"].get("credits").is_none(), + "totals.credits must be ABSENT (not zero) when no row reports credits; \ + got totals = {}", + report["totals"], + ); + // Sanity: existing fields preserved. + assert_eq!(report["totals"]["totalTokens"], 130); +} + +#[test] +fn totals_json_omits_credits_when_all_credits_sum_to_zero() { + // Cross-renderer parity: a Copilot row carrying `Some(0.0)` (e.g. + // a post-cutover day whose `totalNanoAiu == 0` because the user + // only ran free-tier sonnet/haiku) must produce IDENTICAL totals + // JSON shape between direct-agent (`output.rs::totals_json`, + // which omits credits via `if credits > 0.0`) and `--all` + // (`report::totals_json`, same gate). Pre-fix the `--all` path + // emitted `totals: {credits: 0}` while direct-agent omitted the + // key entirely, which broke any `jq` query that branched on the + // key's presence across both report kinds. + + let zero_credit_day = vec![AllRow { + period: "2026-05-15".to_string(), + agent: "copilot", + models_used: vec!["claude-sonnet-4".to_string()], + input_tokens: 1_000, + output_tokens: 200, + cache_creation_tokens: 0, + cache_read_tokens: 0, + total_tokens: 1_200, + total_cost: 0.0, + credits: Some(0.0), // explicit zero AIU charge for the day + metadata: None, + metadata_agents: Some(vec!["copilot"]), + agent_breakdowns: None, + model_breakdowns: Vec::new(), + }]; + + let report = report_json(&zero_credit_day, AgentReportKind::Daily); + assert!( + report["totals"].get("credits").is_none(), + "totals.credits must be ABSENT (not 0) when the SUM of all \ + credits is zero — matching the direct-agent renderer's \ + `if credits > 0.0` gate. Got totals = {}", + report["totals"], + ); + // Sanity: positive numeric fields still emit. + assert_eq!(report["totals"]["totalTokens"], 1_200); +} + +#[test] +fn totals_json_credits_uses_float_representation_matching_direct_renderer() { + // Cross-renderer byte parity for integer-valued credit sums. + // Both renderers must use raw `json!` (not `json_float`) so an + // integer-valued credits sum like 5.0 serializes as `5.0`, not + // `5`. Pre-fix `--all` used `json_float`, which collapses + // integer-valued floats to JSON integers (`5.0` → `5`), + // creating a raw-byte JSON diff against the direct-agent + // renderer (`output.rs::totals_json`, + // raw `json!`). Both representations are semantically + // identical to every JSON consumer, but a literal + // `diff <(ccusage copilot daily --json) <(ccusage daily --all --json)` + // would surface a spurious mismatch. This test pins the JSON + // serialized form, not just the numeric value, by snapshotting + // the serialized string for both per-row metadata.credits and + // totals.credits. + + let copilot_day = vec![AllRow { + period: "2026-05-15".to_string(), + agent: "copilot", + models_used: vec!["claude-opus-4.7-1m-internal".to_string()], + input_tokens: 0, + output_tokens: 0, + cache_creation_tokens: 0, + cache_read_tokens: 0, + total_tokens: 0, + total_cost: 0.05, + credits: Some(5.0), // integer-valued: 5 AI Credits + metadata: None, + metadata_agents: Some(vec!["copilot"]), + agent_breakdowns: None, + model_breakdowns: Vec::new(), + }]; + + let report = report_json(&copilot_day, AgentReportKind::Daily); + let serialized = serde_json::to_string(&report).unwrap(); + assert!( + serialized.contains("\"credits\":5.0"), + "JSON serialization must include `\"credits\":5.0` (not \ + `\"credits\":5`) so `--all` byte-matches direct-agent for \ + integer-valued credit sums. Got serialized = {serialized}", + ); + // Confirm both injection sites emit float-form (per-row metadata + totals). + let count = serialized.matches("\"credits\":5.0").count(); + assert_eq!( + count, 2, + "expected 2 occurrences of `\"credits\":5.0` (one in \ + daily[0].metadata.credits, one in totals.credits); got {count} \ + in serialized = {serialized}", + ); +} + +#[test] +fn build_row_metadata_does_not_inject_agents_for_session_mode_rows() { + // Regression: session-mode rows carry per-row metadata (lastActivity, + // projectPath) but `metadata_agents = None` (cleared by + // `finalize_session_mode_rows` when `kind == Session`). The + // renderer's `build_row_metadata` must NOT inject an "agents" key in + // that case; it should preserve only the existing metadata fields. A + // future refactor that re-enables `metadata_agents` for session mode + // would silently add an "agents" key to non-Copilot session + // --all --json output, which is a user-observable JSON-shape change. + let session_row = vec![AllRow { + period: "session-abc".to_string(), + agent: "claude", + models_used: Vec::new(), + input_tokens: 100, + output_tokens: 50, + cache_creation_tokens: 0, + cache_read_tokens: 0, + total_tokens: 150, + total_cost: 0.123, + credits: None, + metadata: Some(json!({ + "lastActivity": "2026-05-20T12:34:56.000Z", + "projectPath": "/home/user/proj", + })), + metadata_agents: None, // post-finalize_session_mode_rows clear + agent_breakdowns: None, + model_breakdowns: Vec::new(), + }]; + + let report = report_json(&session_row, AgentReportKind::Session); + let row = &report["session"][0]; + let metadata = &row["metadata"]; + + assert!( + metadata["lastActivity"].is_string(), + "lastActivity must be preserved in session-mode metadata; got {metadata}", + ); + assert!( + metadata["projectPath"].is_string(), + "projectPath must be preserved in session-mode metadata; got {metadata}", + ); + assert!( + metadata.get("agents").is_none(), + "agents key must NOT be injected for session-mode rows (where \ + metadata_agents is None); got {metadata}", + ); +} + +#[test] +fn build_row_metadata_injects_agents_for_aggregated_all_rows() { + // Companion to the session-mode test above: aggregated `--all` rows + // come from `AllAccumulator::into_row` with `metadata: None` and + // `metadata_agents: Some(vec![...])`. `build_row_metadata` must + // inject the "agents" key in that case so `--all --json` continues + // to surface which adapters contributed to each aggregate row. + let aggregated_row = vec![AllRow { + period: "2026-05-20".to_string(), + agent: "all", + models_used: Vec::new(), + input_tokens: 100, + output_tokens: 50, + cache_creation_tokens: 0, + cache_read_tokens: 0, + total_tokens: 150, + total_cost: 0.123, + credits: None, + metadata: None, + metadata_agents: Some(vec!["claude", "codex"]), + agent_breakdowns: None, + model_breakdowns: Vec::new(), + }]; + + let report = report_json(&aggregated_row, AgentReportKind::Daily); + let row = &report["daily"][0]; + let metadata = &row["metadata"]; + + assert_eq!( + metadata["agents"], + json!(["claude", "codex"]), + "agents key must be injected for aggregated rows where \ + metadata_agents is Some; got {metadata}", + ); +} + +#[test] +fn finalize_session_mode_rows_clears_metadata_agents() { + // Regression: the renderer-contract test above pins + // `build_row_metadata`'s `None → no agents` branch, but the actual + // production invariant (no `"agents"` key in session-mode --all --json + // output) depends on `load_rows` clearing `metadata_agents = None` for + // every row when `kind == Session`. This test pins THAT clear + // directly. Removing or breaking the clear must fail this assertion + // BEFORE the renderer-contract tests start emitting the wrong JSON + // for real session-mode user output. + let mut rows = vec![ + AllRow { + period: "session-a".to_string(), + agent: "claude", + models_used: Vec::new(), + input_tokens: 100, + output_tokens: 50, + cache_creation_tokens: 0, + cache_read_tokens: 0, + total_tokens: 150, + total_cost: 0.123, + credits: None, + metadata: Some(json!({"lastActivity": "2026-05-20T12:00:00Z"})), + metadata_agents: Some(vec!["claude"]), + agent_breakdowns: None, + model_breakdowns: Vec::new(), + }, + AllRow { + period: "session-b".to_string(), + agent: "copilot", + models_used: Vec::new(), + input_tokens: 200, + output_tokens: 100, + cache_creation_tokens: 0, + cache_read_tokens: 0, + total_tokens: 300, + total_cost: 0.456, + credits: Some(2.5), + metadata: Some(json!({"projectPath": "/home/user/x"})), + metadata_agents: Some(vec!["copilot"]), + agent_breakdowns: None, + model_breakdowns: Vec::new(), + }, + ]; + + finalize_session_mode_rows(&mut rows); + + for (i, row) in rows.iter().enumerate() { + assert!( + row.metadata_agents.is_none(), + "row[{i}] (agent={}, period={}): metadata_agents must be \ + None after finalize_session_mode_rows; got {:?}. Removing \ + or breaking the clear at `load_rows` would make session \ + --all --json emit an unintended `agents` JSON key.", + row.agent, + row.period, + row.metadata_agents, + ); + } + // Sanity: existing metadata fields are preserved (the clear must + // not touch row.metadata). + assert_eq!( + rows[0].metadata.as_ref().unwrap()["lastActivity"], + json!("2026-05-20T12:00:00Z") + ); + assert_eq!( + rows[1].metadata.as_ref().unwrap()["projectPath"], + json!("/home/user/x") + ); +} diff --git a/rust/crates/ccusage/src/adapter/all/types.rs b/rust/crates/ccusage/src/adapter/all/types.rs index 988a3c8..1a1ee2e 100644 --- a/rust/crates/ccusage/src/adapter/all/types.rs +++ b/rust/crates/ccusage/src/adapter/all/types.rs @@ -15,6 +15,16 @@ pub(super) struct AllRow { pub(super) cache_read_tokens: u64, pub(super) total_tokens: u64, pub(super) total_cost: f64, + /// Raw billing-credits count (e.g. GitHub Copilot AI Credits, + /// where 1 AIU = 1 credit = $0.01). First-class field so that the + /// `--all` aggregator can sum credits across agents/periods and + /// the JSON renderer can surface them in `metadata.credits` + /// (per-row, gated on `Option::is_some`) and `totals.credits` + /// (gated on SUM > 0.0), matching the direct per-agent renderer + /// for byte-identical totals JSON. `None` for rows whose source + /// had no credits signal; `Some(0.0)` is distinguishable from + /// absence at the row level. + pub(super) credits: Option, pub(super) metadata: Option, pub(super) metadata_agents: Option>, pub(super) agent_breakdowns: Option>, @@ -69,6 +79,12 @@ pub(super) struct AllAccumulator { cache_read_tokens: u64, total_tokens: u64, total_cost: f64, + /// `None` while no contributor has reported any credits; flips to + /// `Some(sum)` on the first `Some` contribution. This keeps the + /// "credits channel absent" semantic distinct from "credits channel + /// reported zero" — matching the same distinction `Option` + /// carries on each `AllRow`. + credits: Option, models: BTreeSet, agents: BTreeSet<&'static str>, agent_breakdowns: Vec, @@ -83,6 +99,9 @@ impl AllAccumulator { self.cache_read_tokens += row.cache_read_tokens; self.total_tokens += row.total_tokens; self.total_cost += row.total_cost; + if let Some(credits) = row.credits { + self.credits = Some(self.credits.unwrap_or(0.0) + credits); + } self.models.extend(row.models_used.iter().cloned()); if let Some(agents) = row.metadata_agents.as_ref() { self.agents.extend(agents.iter().copied()); @@ -121,6 +140,7 @@ impl AllAccumulator { cache_read_tokens: self.cache_read_tokens, total_tokens: self.total_tokens, total_cost: self.total_cost, + credits: self.credits, metadata: None, metadata_agents: Some(self.agents.into_iter().collect()), agent_breakdowns: Some(agent_breakdowns), @@ -136,6 +156,9 @@ fn merge_agent_breakdown(target: &mut AllRow, source: AllRow) { target.cache_read_tokens += source.cache_read_tokens; target.total_tokens += source.total_tokens; target.total_cost += source.total_cost; + if let Some(credits) = source.credits { + target.credits = Some(target.credits.unwrap_or(0.0) + credits); + } let mut models: BTreeSet = target.models_used.drain(..).collect(); models.extend(source.models_used); target.models_used = models.into_iter().collect(); diff --git a/rust/crates/ccusage/src/adapter/copilot/README.md b/rust/crates/ccusage/src/adapter/copilot/README.md new file mode 100644 index 0000000..20a2f4c --- /dev/null +++ b/rust/crates/ccusage/src/adapter/copilot/README.md @@ -0,0 +1,224 @@ +# GitHub Copilot CLI Source + +Data source: + +```text +${COPILOT_CONFIG_DIR:-~/.copilot}/session-state//events.jsonl +``` + +The Copilot CLI writes `session-state//events.jsonl` automatically during each CLI session, appending a `session.shutdown` event on graceful exit. + +## session-state schema + +Relevant JSONL event: + +- `type === "session.shutdown"` (other event types — `tool.execution_start`, + `assistant.message`, etc. — may contain the literal string + `"session.shutdown"` inside `arguments.command` or `content`; the parser + requires the top-level `type` field after JSON parsing, never trusts the + substring alone). +- `id` — per-event UUID, used as part of the dedup key + (`shutdown:{session_id}:{event.id}:{model}` for token-bearing rows; + `session_id` is prefixed as defense-in-depth against a future Copilot + CLI that might scope event ids per-session). +- `timestamp` — RFC3339 with ms (`"2026-05-02T15:27:09.013Z"`). +- `data.modelMetrics` — map keyed by Copilot model id; each value carries + `usage.{inputTokens, outputTokens, cacheReadTokens, cacheWriteTokens, + reasoningTokens}` and `requests.{count, cost}`. + +### Token mapping (session-state) + +`usage.inputTokens` in this schema is inclusive of **both** `cacheReadTokens` +and `cacheWriteTokens`. + +| Field on `LoadedEntry` | Source | +| -------------------------------- | --------------------------------------------------------------------------- | +| `input_tokens` | `usage.inputTokens − usage.cacheReadTokens − usage.cacheWriteTokens` (saturating) | +| `output_tokens` | `usage.outputTokens` | +| `cache_read_tokens` | `usage.cacheReadTokens` | +| `cache_creation_input_tokens` | `usage.cacheWriteTokens` | +| `reasoning_output_tokens` | provider-dependent — see below | + +`data.tokenDetails` exists in the schema but is **intentionally not used as a +source**: empirical verification showed `usage.*` and `tokenDetails.*` are +independent snapshots that diverge in ~31% of resumed-session rows. We use +`usage.*` consistently across all four token fields. + +### Reasoning tokens + +Provider conventions differ. Verified locally across the full session-state +corpus: + +| Provider | Convention | Rule | +| ------------------------- | ------------------------------------------------------- | --------------------------------- | +| `claude-*` (Anthropic) | Extended-thinking tokens included in `outputTokens` | `reasoning_output_tokens = 0` | +| `gpt-*` (OpenAI) | `reasoning_tokens` is a subset of `output_tokens` | `reasoning_output_tokens = 0` | +| `gemini-*` (Google) | `thoughtsTokenCount` is a separate field from output | `reasoning_output_tokens = usage.reasoningTokens` | +| Anything else (default) | Treated like Claude/GPT — the subset rule cannot over-count | `reasoning_output_tokens = 0` | + +### Skip rule + +A `modelMetrics` row is skipped when **all** of the following are true: + +1. All non-reasoning token fields are zero (`input`, `output`, `cache_read`, + `cache_write`), AND for Gemini models `reasoning_tokens` is also zero. +2. `requests.count` is zero. +3. `metrics.totalNanoAiu` is absent or zero. + +Matches PR #957's `data-loader.ts` inline skip-row predicate, extended with the AIU +carve-out so that real-data credit-only rows (zero tokens, zero requests, +non-zero `totalNanoAiu`) survive. The reasoning-token clause is +provider-gated to stay symmetric with `build_session_state_entry`: for +Gemini the builder preserves `reasoning_tokens` verbatim (separate field +from output), so the skip rule counts it as usage; for OpenAI/Anthropic +the builder discards it (already subsumed into `output_tokens`), so the +skip rule ignores it to avoid surfacing all-zero phantom rows. See +`keeps_zero_token_row_when_per_model_total_nano_aiu_is_present`, +`keeps_gemini_row_with_only_reasoning_tokens`, and +`skips_non_gemini_row_with_only_reasoning_tokens` for the matching +regressions. + +### Resumed sessions and dedup-key design + +A single `events.jsonl` may contain multiple `session.shutdown` events (the user +re-opened the same session UUID multiple times). Each shutdown is a +**per-process snapshot** — token counts are NOT cumulative across resumes. The +parser emits one entry per `(session_id, event.id, model)` triple so the +resumed-session totals are summed correctly at report time. + +The dedup-key selector chooses between two key shapes for each surviving row, +and the two shapes deliberately encode **opposite beliefs about what a duplicate +shutdown means** — because real-data shapes differ between the two paths: + +- **Token-bearing / priced rows** key on `shutdown:{session_id}:{event_id}:{model}`. + Two shutdowns with distinct event ids are treated as distinct charges (sum at + report time), even if their token counts happen to coincide. This is correct + because per-process snapshots commonly produce near-identical counts when a + user resumes a similar workload, and treating them as duplicates would + silently under-count usage. The `session_id` prefix is defense-in-depth: + today every observed `event.id` is a globally-unique UUID, but prefixing + with `session_id` guards against a hypothetical future Copilot CLI that + scopes event ids per-session, which would otherwise silently collapse + distinct sessions' rows in the loader's final `HashMap`-keyed dedup. Pinned + by `token_bearing_rows_keep_event_id_dedup_key_not_content_based` and + `treats_resumed_session_shutdowns_as_distinct_entries`. +- **Credit-only zero-token rows** key on + `credit-shutdown:{session_id}:{model}:{naiu}` — **deliberately omitting + `event_id`**. The loader's `HashMap::insert` collapse is last-wins, so + duplicate AIU snapshots with identical `totalNanoAiu` collapse instead of + double-counting. Pinned by + `auto_mode_dedupes_duplicate_credit_only_rows_within_same_session` and + `credit_only_rows_with_identical_naiu_but_distinct_event_ids_are_treated_as_duplicates`. + +**The asymmetry is intentional.** Token rows trust event ids because their +data shape (per-process snapshots) makes coincidence-collision a far more +likely failure mode than missed-duplicate. Credit-only rows distrust event +ids because paired snapshots make the opposite true. + +The aggregate-credit synthetic entry (emitted only when no per-model row +carries a priced billing signal — see `parse_session_state_file`'s +suppression guard) uses the same content-based key family +(`credit-aggregate:{session_id}:{nano_aiu}`) to mirror the credit-only +"paired snapshot" semantics. + +### Date filter must run before dedup + +The credit-only key shape above (which deliberately omits `event_id`) makes +the loader's `HashMap`-based dedup collapse **last-wins by parse order**: +two credit-only rows in the same session with the same `(model, naiu)` but +distinct timestamps collapse into whichever was inserted last. That's the +intended behaviour for paired snapshots inside an active date range — but +if the two rows straddle a `--since` / `--until` boundary, applying the +date filter **after** the dedup HashMap could keep the out-of-range row, +drop it on the filter, and silently lose the in-range row's credits +entirely. + +The loader therefore applies the `--since` / `--until` filter to the +`CopilotUsageEntry` vector **before** the dedup `HashMap::insert` collapse. +Each surviving entry already satisfies the date range, so the collapse can +never pick an out-of-range winner. Token-bearing rows (event-id keyed) are +immune to this ordering bug, but the filter applies uniformly to keep the +loader-layer surface symmetric across both key families. The downstream +`filter_loaded_entries_by_date` calls in `copilot::run` and the cross-source +aggregator (`adapter::all::loader`) remain in place as defense-in-depth +no-ops once the loader has filtered, and to keep the user-facing +`LoadedEntry` surface uniform with the other adapters. Pinned by +`date_filter_runs_before_credit_only_dedup_collapse_to_preserve_in_range_row`. + +## Model normalization + +The adapter ships `normalize_copilot_model()` for pricing-lookup callers. The +function is applied **only inside `loader.rs::usage_entry_to_loaded`** for both +`calculate_cost_for_usage` and `missing_pricing_model_for_usage` call sites — +the entry itself keeps the raw model name so reports, JSON and `modelsUsed` +preserve source fidelity. + +Rules: + +1. Strip Copilot routing suffixes in this order: `-1m-internal`, `-internal`, + `-xhigh`, `-high`, `-1m`. Required because + `pricing::suffix_starts_with_numeric_model_version` rejects suffixes that + begin with another digit, so without stripping the `-1m` family of variants + no pricing entry resolves. +2. For `claude-*` names, convert version-number dots to dashes (e.g. + `claude-opus-4.7` → `claude-opus-4-7`). Matches the canonical LiteLLM keys. +3. GPT names pass through unchanged — LiteLLM keeps them dotted. +4. Unknown prefixes pass through unchanged. + +## Cost modes + +| `--mode` | Behavior for Copilot | +| -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `auto` | True bill, billing-field-aware: AIU when present (typically post-cutover) → premium-requests × $0.04 when present (typically pre-cutover) → token-priced via LiteLLM (neither billing field). The default. Free-tier rows (`requests.cost == 0`) bill as $0. | +| `display`| Source-precomputed only: AIU → premium-requests → $0. No token-priced fallback. | +| `calculate` / `api` | Always token-priced via LiteLLM (`normalize_copilot_model()` applied at both `calculate_cost_for_usage` and `missing_pricing_model_for_usage` call sites). | + +The billing-field-aware default reflects that GitHub Copilot switched billing +models on June 1, 2026: pre-cutover sessions were billed in "premium requests" +with per-model multipliers at $0.04/overage-request, and post-cutover sessions +bill in AI Units (1 AIU = 1 credit = $0.01). The Copilot CLI records each +session's own billing data, so `auto` surfaces what GitHub actually charged +you for that session. + +**The dispatch keys off field presence, not the cutover date.** The +loader never compares `entry.timestamp` to June 1, 2026 — it just asks +"did this row ship `totalNanoAiu`?" and picks AIU billing if so. The cutover +date is the *why* behind the two billing columns existing in the wire +schema; it is not a branching condition in the code. This shape is more +robust than a date check: it correctly handles a pre-cutover session that +happens to ship AIU (rare but possible if GitHub ever backfills) and +generalises to a hypothetical future third billing channel without a +schema-version migration. + +`PREMIUM_REQUEST_COST_USD = $0.04` and `AI_CREDIT_COST_USD = $0.01` are +GitHub's published external pricing rates, not contracts encoded in the +CLI's wire format. If GitHub adjusts either rate, `auto`/`display` will +mis-bill until the constants are updated. The mitigation users have today +is `--mode api` (alias of `calculate`): that path bills from token counts +via LiteLLM and does not depend on either constant. + +`LoadedEntry.credits` is populated independently of `--mode` whenever the +source carried `totalNanoAiu`, so JSON consumers see the raw credit count +regardless of mode selection. + +The `missing_pricing_model` warning never fires for the AIU and premium-request +branches of `auto`/`display` because they don't consult LiteLLM — those +branches return `None` directly. The shared +`cost.rs::missing_pricing_model_for_usage` early-return remains intact so other +adapters still see legitimate missing-pricing warnings when their token-pricing +fallback can't resolve a model. + +## Environment variables + +| Variable | Effect | +| -------------------- | --------------------------------------------------------------- | +| `COPILOT_CONFIG_DIR` | Override the base Copilot directory (defaults to `~/.copilot`). | + +## Legacy OpenTelemetry environment variables + +ccusage no longer reads OpenTelemetry exports — the production loader uses +`~/.copilot/session-state//events.jsonl` directly. The legacy OTel +environment variables (`COPILOT_OTEL_FILE_EXPORTER_PATH`, `COPILOT_OTEL_DEDUP`, +`COPILOT_PREFER_OTEL`) are inert; if any of them are set when `ccusage copilot` +runs, a one-shot stderr warning explains they are ignored. Unset them, or set +`LOG_LEVEL=0`, to silence the warning. diff --git a/rust/crates/ccusage/src/adapter/copilot/loader.rs b/rust/crates/ccusage/src/adapter/copilot/loader.rs index a04b6d5..26f0082 100644 --- a/rust/crates/ccusage/src/adapter/copilot/loader.rs +++ b/rust/crates/ccusage/src/adapter/copilot/loader.rs @@ -1,21 +1,28 @@ -use std::{path::Path, sync::Arc}; +use std::{collections::HashMap, sync::Arc}; use jiff::tz::TimeZone as JiffTimeZone; use super::{ - parser::{CopilotUsageEntry, parse_otel_file}, - paths::paths, + parser::{CopilotUsageEntry, normalize_copilot_model, parse_session_state_file}, + paths::session_state_paths, }; use crate::{ LoadedEntry, Result, TokenUsageRaw, UsageEntry, UsageMessage, calculate_cost_for_usage, - cli::CostMode, debug_log, format_date_tz, missing_pricing_model_for_usage, parse_tz, - read_files_parallel, + cli::CostMode, format_date_tz, missing_pricing_model_for_usage, parse_tz, }; +/// Pre-June-2026 premium-request USD rate; `requests.cost` already includes +/// Copilot's per-model multipliers. +const PREMIUM_REQUEST_COST_USD: f64 = 0.04; + +/// Post-June-2026 AI Credit USD rate; `totalNanoAiu` is nano-AIU. +const AI_CREDIT_COST_USD: f64 = 0.01; + pub(crate) fn load_entries( shared: &crate::cli::SharedArgs, pricing: &crate::PricingMap, ) -> Result> { + crate::adapter::copilot::warn_about_inert_legacy_env_vars_once(); crate::progress::track_usage_load( crate::progress::UsageLoadAgent::Copilot, shared.json, @@ -28,41 +35,54 @@ fn load_entries_inner( pricing: &crate::PricingMap, ) -> Result> { let tz = parse_tz(shared.timezone.as_deref()); - let files = paths()?; - // Read OTEL files in parallel; entries keep their original file order before - // the stable sort, so output is identical to the sequential read. - let loaded = read_files_parallel(&files, shared.single_thread, |path| { - read_otel_file(path, tz.as_ref(), shared.mode, pricing).unwrap_or_else(|error| { - debug_log( - shared, - format!( - "Failed to read Copilot OTEL file {}: {error}", - path.display() - ), - ); - Vec::new() + + let mut entries: Vec = Vec::new(); + for path in session_state_paths()? { + match parse_session_state_file(&path) { + Ok(file_entries) => entries.extend(file_entries), + Err(err) => { + if crate::log_level() != Some(0) { + eprintln!( + "warning: failed to read GitHub Copilot session-state file \ + {}: {err}. Skipping this file; other sessions will still \ + be reported. Set LOG_LEVEL=0 to silence.", + path.display(), + ); + } + } + } + } + + // Filter before content-key dedup so out-of-range twins cannot win last-wins collapse. + if shared.since.is_some() || shared.until.is_some() { + entries.retain(|entry| { + let date = format_date_tz(entry.timestamp, tz.as_ref()).replace('-', ""); + shared.since.as_ref().is_none_or(|since| &date >= since) + && shared.until.as_ref().is_none_or(|until| &date <= until) + }); + } + + let mut deduped: HashMap = HashMap::new(); + for entry in entries { + deduped.insert(entry.dedup_key.clone(), entry); + } + + let mut entries: Vec = deduped + .into_values() + .map(|entry| usage_entry_to_loaded(entry, tz.as_ref(), shared.mode, pricing)) + .collect(); + entries.sort_by(|a, b| { + a.timestamp.cmp(&b.timestamp).then_with(|| { + a.data + .message + .id + .as_deref() + .cmp(&b.data.message.id.as_deref()) }) }); - let mut entries = Vec::new(); - for file_entries in loaded { - entries.extend(file_entries); - } - entries.sort_by_key(|entry| entry.timestamp); Ok(entries) } -fn read_otel_file( - path: &Path, - tz: Option<&JiffTimeZone>, - mode: CostMode, - pricing: &crate::PricingMap, -) -> Result> { - Ok(parse_otel_file(path)? - .into_iter() - .map(|entry| usage_entry_to_loaded(entry, tz, mode, pricing)) - .collect()) -} - fn usage_entry_to_loaded( entry: CopilotUsageEntry, tz: Option<&JiffTimeZone>, @@ -82,13 +102,23 @@ fn usage_entry_to_loaded( cache_creation: None, ..usage }; + let model_for_data = if entry.model.is_empty() { + // Synthetic aggregate-credit rows have no model; don't surface a blank model. + None + } else { + Some(entry.model.clone()) + }; let data = UsageEntry { session_id: Some(entry.session_id.clone()), timestamp: entry.timestamp_text, version: None, message: UsageMessage { usage, - model: Some(entry.model.clone()), + // Preserve raw model name in JSON / `modelsUsed` / table for + // source fidelity. Normalization happens only at the pricing + // call sites below (Copilot routing suffixes are stripped for + // LiteLLM lookup but kept in user-visible output). + model: model_for_data.clone(), id: Some(entry.dedup_key), }, cost_usd: None, @@ -96,9 +126,56 @@ fn usage_entry_to_loaded( is_api_error_message: None, is_sidechain: None, }; - let cost = calculate_cost_for_usage(Some(&entry.model), cost_usage, None, mode, Some(pricing)); - let missing_pricing_model = - missing_pricing_model_for_usage(Some(&entry.model), cost_usage, None, mode, Some(pricing)); + + let credits = entry.nano_aiu.map(|naiu| naiu as f64 / 1e9); + let credit_cost = credits.map(|c| c * AI_CREDIT_COST_USD); + let has_aiu = credits.is_some(); + + let premium_cost = entry + .premium_request_cost + .map(|requests| requests * PREMIUM_REQUEST_COST_USD); + let has_premium_data = premium_cost.is_some(); + + let (cost, missing_pricing_model) = if entry.model.is_empty() { + let cost = match mode { + CostMode::Auto | CostMode::Display => credit_cost.unwrap_or(0.0), + CostMode::Calculate => 0.0, + }; + (cost, None) + } else { + match mode { + CostMode::Display => { + let cost = credit_cost.or(premium_cost).unwrap_or(0.0); + (cost, None) + } + CostMode::Auto if has_aiu => ( + credit_cost.expect("has_aiu guards credit_cost.is_some()"), + None, + ), + CostMode::Auto if has_premium_data => ( + premium_cost.expect("has_premium_data guards premium_cost.is_some()"), + None, + ), + CostMode::Auto | CostMode::Calculate => { + let normalized = normalize_copilot_model(&entry.model); + let cost = calculate_cost_for_usage( + Some(normalized.as_ref()), + cost_usage, + None, + CostMode::Calculate, + Some(pricing), + ); + let missing_pricing_model = missing_pricing_model_for_usage( + Some(normalized.as_ref()), + cost_usage, + None, + CostMode::Calculate, + Some(pricing), + ); + (cost, missing_pricing_model) + } + } + }; LoadedEntry { date: format_date_tz(entry.timestamp, tz), timestamp: entry.timestamp, @@ -107,208 +184,1208 @@ fn usage_entry_to_loaded( project_path: Arc::from("GitHub Copilot CLI"), cost, extra_total_tokens: entry.reasoning_output_tokens, - credits: None, + credits, message_count: None, - model: Some(entry.model), + // Reports show the raw model name (`claude-opus-4.7-1m-internal`), + // not the normalized pricing key — matches PR #957's choice. + model: model_for_data, data, usage_limit_reset_time: None, missing_pricing_model, } } -#[cfg(test)] -use super::report::{report_from_rows, summarize_entries}; - #[cfg(test)] mod tests { - use ccusage_test_support::fs_fixture; + use std::ffi::OsStr; + use serde_json::json; - use super::super::parser::parse_otel_file; use super::*; - use crate::cli::AgentReportKind; + + use ccusage_test_support::EnvVarGuard; + + use super::super::paths::COPILOT_CONFIG_DIR_ENV; + use crate::cli::SharedArgs; + + fn env_scope(overrides: &[(&'static str, Option<&str>)]) -> EnvVarGuard { + let overrides = overrides + .iter() + .map(|(key, value)| (*key, value.map(OsStr::new))) + .collect::>(); + EnvVarGuard::set_many(&overrides) + } + + fn shared_args_default() -> SharedArgs { + SharedArgs { + json: true, // suppress progress UI under tests + offline: true, + mode: CostMode::Calculate, + ..SharedArgs::default() + } + } + + fn shutdown_line( + event_id: &str, + ts: &str, + model: &str, + in_tokens: u64, + out_tokens: u64, + ) -> String { + // `requests.cost` is OMITTED — not set to 0 — so the per-model row + // genuinely has `premium_request_cost = None` once parsed. This + // exercises the "no precomputed cost field" forward-compat shape; + // `cost: Some(0.0)` would flatten to the same `$0` in Display via + // `credit_cost.or(premium_cost).unwrap_or(0.0)`, but it routes + // through the `has_premium_data == true` arm and misrepresents the + // genuinely-absent narrative. + json!({ + "type": "session.shutdown", + "id": event_id, + "timestamp": ts, + "data": {"modelMetrics": { + model: { + "usage": { + "inputTokens": in_tokens, + "outputTokens": out_tokens, + "cacheReadTokens": 0u64, + "cacheWriteTokens": 0u64, + "reasoningTokens": 0u64 + }, + "requests": {"count": 1} + } + }} + }) + .to_string() + } + + /// Sets `COPILOT_CONFIG_DIR` to a fixture root containing the + /// `session-state//events.jsonl` files described by the test input. + fn build_session_fixture(session_files: &[(&str, &str)]) -> ccusage_test_support::Fixture { + let fixture = ccusage_test_support::Fixture::new(); + for (uuid, contents) in session_files { + let _ = fixture.write_file(format!("session-state/{uuid}/events.jsonl"), *contents); + } + fixture + } #[test] - fn parses_copilot_chat_spans() { - let fixture = fs_fixture!({ - "copilot.jsonl": [ - json!({ "type": "metric", "name": "gen_ai.client.token.usage" }).to_string(), + fn loader_dedup_keeps_distinct_sessions_with_colliding_event_ids() { + // Defense-in-depth: the parser's token-bearing dedup key is + // `shutdown:{session_id}:{event_id}:{model}` precisely so that if + // a future Copilot CLI release ever scopes `event.id` per-session + // (instead of the currently-observed global UUIDs), two rows from + // different sessions with the same event id will NOT collapse in + // the loader's HashMap. This fixture creates that exact scenario + // and asserts both rows survive — guarding against silent + // under-counting if the upstream invariant changes. + let make_shutdown = || { + format!( + "{}\n", json!({ - "type": "span", - "traceId": "trace-1", - "spanId": "span-1", - "name": "chat claude-sonnet-4", - "endTime": [1_775_934_264_u64, 967_317_833_u64], - "attributes": { - "gen_ai.operation.name": "chat", - "gen_ai.request.model": "claude-sonnet-4", - "gen_ai.response.model": "claude-sonnet-4", - "gen_ai.conversation.id": "conv-1", - "gen_ai.usage.input_tokens": 19_452, - "gen_ai.usage.output_tokens": 281, - "gen_ai.usage.cache_read.input_tokens": 123, - "gen_ai.usage.cache_creation.input_tokens": 25, - "gen_ai.usage.reasoning.output_tokens": 128, - }, + "type": "session.shutdown", + // Identical event.id across both sessions on purpose. + "id": "evt-collision", + "timestamp": "2026-05-02T15:27:09.013Z", + "data": {"modelMetrics": { + "claude-opus-4.7": { + "usage": { + "inputTokens": 1_000u64, + "outputTokens": 100u64, + "cacheReadTokens": 0u64, + "cacheWriteTokens": 0u64, + "reasoningTokens": 0u64 + }, + "requests": {"count": 1, "cost": 1} + } + }} }) - .to_string(), - ] - .join("\n"), - }); - let file = fixture.path("copilot.jsonl"); + ) + }; + let fixture = build_session_fixture(&[ + ("session-A", &make_shutdown()), + ("session-B", &make_shutdown()), + ]); + let _env = env_scope(&[( + COPILOT_CONFIG_DIR_ENV, + Some(fixture.root().to_str().unwrap()), + )]); - let entries = parse_otel_file(&file).unwrap(); + let pricing = crate::PricingMap::default(); + let entries = load_entries_inner(&shared_args_default(), &pricing).unwrap(); + // Without `session_id` in the dedup key, both rows would collapse + // to a single HashMap entry and we'd lose half the usage. With + // it, both survive. + assert_eq!(entries.len(), 2, "got {entries:?}"); + let session_ids: std::collections::HashSet<_> = + entries.iter().map(|e| e.session_id.as_ref()).collect(); + assert_eq!( + session_ids, + ["session-A", "session-B"].into_iter().collect() + ); + } - assert_eq!(entries.len(), 1); - assert_eq!(entries[0].timestamp_text, "2026-04-11T19:04:24.967Z"); - assert_eq!(entries[0].session_id, "conv-1"); - assert_eq!(entries[0].model, "claude-sonnet-4"); - assert_eq!(entries[0].input_tokens, 19_329); - assert_eq!(entries[0].output_tokens, 281); - assert_eq!(entries[0].cache_creation_tokens, 25); - assert_eq!(entries[0].cache_read_tokens, 123); - assert_eq!(entries[0].reasoning_output_tokens, 128); - assert_eq!(entries[0].dedup_key, "trace-1:span-1"); + #[test] + fn loader_sort_is_deterministic_for_equal_timestamps() { + // Two rows sharing a millisecond timestamp must emit in the same + // order every run. Without a secondary sort key, upstream + // `HashMap::into_values` iteration order would make the tie + // non-deterministic, breaking JSON-snapshot stability and + // diff-friendliness of `--json` output. + let same_ts = "2026-05-02T15:27:09.013Z"; + let make_row = |event_id: &str, model: &str| { + json!({ + "type": "session.shutdown", + "id": event_id, + "timestamp": same_ts, + "data": {"modelMetrics": { + model: { + "usage": { + "inputTokens": 100u64, + "outputTokens": 50u64, + "cacheReadTokens": 0u64, + "cacheWriteTokens": 0u64, + "reasoningTokens": 0u64 + }, + "requests": {"count": 1, "cost": 1} + } + }} + }) + .to_string() + }; + let fixture = build_session_fixture(&[( + "session-tied", + &format!( + "{}\n{}\n{}\n", + make_row("evt-c", "claude-sonnet-4.5"), + make_row("evt-a", "claude-opus-4.7"), + make_row("evt-b", "claude-haiku-4.5"), + ), + )]); + let _env = env_scope(&[( + COPILOT_CONFIG_DIR_ENV, + Some(fixture.root().to_str().unwrap()), + )]); + + let pricing = crate::PricingMap::default(); + // Run the loader multiple times; every run must produce the same + // ordering across equal-timestamp rows. + let runs: Vec> = (0..5) + .map(|_| { + load_entries_inner(&shared_args_default(), &pricing) + .unwrap() + .into_iter() + .map(|e| e.data.message.id.unwrap_or_default()) + .collect() + }) + .collect(); + for (i, run) in runs.iter().enumerate() { + assert_eq!( + run, &runs[0], + "run {i} differs from run 0; loader sort is non-deterministic" + ); + } + // And concretely: the order must follow the secondary key + // (`dedup_key`, which sorts lexicographically by event_id within + // the same session). Token-bearing keys are + // `shutdown:{session}:{event}:{model}`, so for session "session-tied" + // the lexicographic order is evt-a < evt-b < evt-c regardless of + // model name. + let ids = &runs[0]; + let positions: Vec<_> = ids + .iter() + .map(|id| id.split(':').nth(2).unwrap_or("").to_string()) + .collect(); + assert_eq!(positions, vec!["evt-a", "evt-b", "evt-c"]); } #[test] - fn suppresses_lower_priority_records_for_same_response() { - let fixture = fs_fixture!({ - "copilot.jsonl": [ + fn pricing_resolves_via_normalization_for_internal_suffix_models() { + let fixture = build_session_fixture(&[( + "session-normalize", + &format!( + "{}\n", json!({ - "type": "span", - "traceId": "trace-dupe", - "spanId": "agent-1", - "name": "invoke_agent GitHub Copilot Chat", - "attributes": { - "gen_ai.operation.name": "invoke_agent", - "gen_ai.response.model": "gpt-5.4-mini", - "gen_ai.conversation.id": "conv-dupe", - "gen_ai.response.id": "resp-dupe", - "gen_ai.usage.input_tokens": 100, - "gen_ai.usage.output_tokens": 30, + "type": "session.shutdown", + "id": "evt-norm", + "timestamp": "2026-05-02T15:27:09.013Z", + "data": {"modelMetrics": { + "claude-opus-4.7-1m-internal": { + "usage": { + "inputTokens": 1_000u64, + "outputTokens": 100u64, + "cacheReadTokens": 0u64, + "cacheWriteTokens": 0u64, + "reasoningTokens": 0u64 + }, + "requests": {"count": 1, "cost": 0} + } + }} + }) + ), + )]); + let _env = env_scope(&[( + COPILOT_CONFIG_DIR_ENV, + Some(fixture.root().to_str().unwrap()), + )]); + + // Minimal embedded pricing keyed by the normalized name. + let mut pricing = crate::PricingMap::default(); + pricing.load_json( + r#"{"claude-opus-4-7":{"input_cost_per_token":0.0000015,"output_cost_per_token":0.0000075}}"#, + ); + + let entries = load_entries_inner(&shared_args_default(), &pricing).unwrap(); + assert_eq!(entries.len(), 1); + let entry = &entries[0]; + // Raw model preserved for display (normalization happens only at + // the pricing call sites, not on the user-visible field). + assert_eq!( + entry.model.as_deref(), + Some("claude-opus-4.7-1m-internal"), + "raw model name must reach LoadedEntry.model" + ); + // Cost > 0 — pricing lookup succeeded via normalize_copilot_model. + assert!( + entry.cost > 0.0, + "expected non-zero cost, got {}", + entry.cost + ); + // missing_pricing_model must be None — otherwise the breakdown + // branch of `UsageAccumulator::add_entry` (summary.rs) would flip + // `breakdown.missing_pricing` and emit a contradictory warning. + // Pins the invariant that BOTH the pricing call site AND the + // missing-pricing-detection call site receive the normalized model + // name (loader.rs's token-priced arm). + assert!( + entry.missing_pricing_model.is_none(), + "expected missing_pricing_model None, got {:?}", + entry.missing_pricing_model + ); + } + + #[test] + fn display_mode_returns_zero_for_session_state_without_aiu() { + // Session-state shutdowns without `totalNanoAiu` produce zero cost in + // display mode (no precomputed cost field exists) — same convention + // as Gemini and Kimi adapters whose sources have no precomputed cost. + // The `shutdown_line` helper genuinely omits `requests.cost`, so + // `premium_request_cost == None` and Display reaches `0.0` via + // `credit_cost.or(premium_cost).unwrap_or(0.0)` taking the + // `None.or(None)` path — pinning the genuinely-absent shape rather + // than a `Some(0.0)` masquerade. + let fixture = build_session_fixture(&[( + "session-display", + &format!( + "{}\n", + shutdown_line( + "evt-1", + "2026-05-02T15:27:09.013Z", + "claude-sonnet-4", + 500, + 50 + ) + ), + )]); + let _env = env_scope(&[( + COPILOT_CONFIG_DIR_ENV, + Some(fixture.root().to_str().unwrap()), + )]); + + let mut args = shared_args_default(); + args.mode = CostMode::Display; + let pricing = crate::PricingMap::default(); + let entries = load_entries_inner(&args, &pricing).unwrap(); + assert_eq!(entries.len(), 1); + assert_eq!( + entries[0].cost, 0.0, + "Display mode must yield 0 for session-state data without AIU" + ); + // The genuinely-absent `requests.cost` and `totalNanoAiu` are + // pinned at the helper site (`shutdown_line` omits `cost`; this + // test omits `totalNanoAiu`); the loaded view collapses them to + // `cost = 0.0` via `credit_cost.or(premium_cost).unwrap_or(0.0)` + // taking the `None.or(None)` path — not the `Some(0.0)` masquerade. + } + + // ----- AIU billing under --mode auto ----- + + fn shutdown_with_credits_line( + event_id: &str, + ts: &str, + model: &str, + in_tokens: u64, + out_tokens: u64, + naiu: u64, + request_count: u64, + ) -> String { + json!({ + "type": "session.shutdown", + "id": event_id, + "timestamp": ts, + "data": {"modelMetrics": { + model: { + "usage": { + "inputTokens": in_tokens, + "outputTokens": out_tokens, + "cacheReadTokens": 0u64, + "cacheWriteTokens": 0u64, + "reasoningTokens": 0u64 }, + "requests": {"count": request_count, "cost": 0}, + "totalNanoAiu": naiu + } + }} + }) + .to_string() + } + + #[test] + fn auto_mode_bills_zero_token_credit_only_row_from_aiu() { + // Real-data shape: zero tokens, zero requests, non-null per-model + // totalNanoAiu = 154_481_000_000 ≈ $1.54481. The parser must keep + // the row (skip rule already accommodates AIU presence) and Auto + // must bill it from AIU. + let fixture = build_session_fixture(&[( + "session-credit-only", + &format!( + "{}\n", + shutdown_with_credits_line( + "evt-only", + "2026-05-20T16:01:29.481Z", + "claude-opus-4.7-1m-internal", + 0, + 0, + 154_481_000_000, + 0, + ) + ), + )]); + let _env = env_scope(&[( + COPILOT_CONFIG_DIR_ENV, + Some(fixture.root().to_str().unwrap()), + )]); + + let mut args = shared_args_default(); + args.mode = CostMode::Auto; + let pricing = crate::PricingMap::default(); + let entries = load_entries_inner(&args, &pricing).unwrap(); + assert_eq!(entries.len(), 1); + assert!((entries[0].cost - 1.54481).abs() < 1e-9); + assert_eq!(entries[0].credits, Some(154.481)); + } + + #[test] + fn auto_mode_dedupes_duplicate_credit_only_rows_within_same_session() { + // Two distinct shutdown events with identical per-model totalNanoAiu + // (same shape as real-data `1135875b-…` pair). The content-based + // dedup key + loader HashMap must collapse them to one entry, so the + // total cost is `1.54481`, not `2 × 1.54481`. + let dup = shutdown_with_credits_line( + "evt-first", + "2026-05-20T16:01:29.481Z", + "claude-opus-4.7-1m-internal", + 0, + 0, + 154_481_000_000, + 0, + ); + let dup2 = shutdown_with_credits_line( + "evt-second", + "2026-05-20T18:08:30.785Z", + "claude-opus-4.7-1m-internal", + 0, + 0, + 154_481_000_000, + 0, + ); + let fixture = build_session_fixture(&[("session-dup", &format!("{dup}\n{dup2}\n"))]); + let _env = env_scope(&[( + COPILOT_CONFIG_DIR_ENV, + Some(fixture.root().to_str().unwrap()), + )]); + + let mut args = shared_args_default(); + args.mode = CostMode::Auto; + let pricing = crate::PricingMap::default(); + let entries = load_entries_inner(&args, &pricing).unwrap(); + assert_eq!( + entries.len(), + 1, + "expected the duplicate pair to collapse into one entry" + ); + assert!((entries[0].cost - 1.54481).abs() < 1e-9); + } + + #[test] + fn credit_only_rows_with_identical_naiu_but_distinct_event_ids_are_treated_as_duplicates() { + // Locks the deliberate dedup-key design choice documented in + // `adapter/copilot/README.md` under "Resumed sessions and dedup-key + // design": credit-only rows use `credit-shutdown:{session}:{model}:{naiu}` + // and OMIT `event_id`, because real-data ships them in paired + // snapshots with distinct event ids but identical naiu (the + // 1135875b-… / 76dc438a-… pattern; ~$2.65 of credits would be + // double-billed by event-id-based keying in the local 200-file + // corpus). + // + // This test makes the intentional under-count behavior explicit: + // if a future Copilot CLI ever ships TWO genuinely distinct + // credit-only charges in the same session that happen to share + // model + naiu, the loader will collapse them to ONE entry. This + // is the deliberate trade-off — the alternative (keying on + // event_id) would silently double-bill every real-data paired + // snapshot, which is the failure mode the design optimises + // against. The collapse surfaces in `credits` JSON output (the + // soft signal) rather than producing a silent wrong number. + // + // Companion to (token-bearing) `loader_dedup_keeps_distinct_sessions_with_colliding_event_ids` + // and (parser-side) `dedupes_identical_credit_only_rows_within_same_session`. + // This test pins the SAME shape but at the LOADER HashMap-collapse + // boundary and asserts the resulting cost (Auto mode bills + // 154.481 credits × $0.01 = $1.54481 — ONCE, not twice). + let first = shutdown_with_credits_line( + "evt-genuine-charge-a", + "2026-05-20T10:00:00.000Z", + "claude-opus-4.7-1m-internal", + 0, + 0, + 154_481_000_000, + 0, + ); + let second = shutdown_with_credits_line( + "evt-genuine-charge-b", + "2026-05-21T10:00:00.000Z", // Note: a full day later — distinct + "claude-opus-4.7-1m-internal", + 0, + 0, + 154_481_000_000, // ...but coincidentally identical naiu. + 0, + ); + let fixture = build_session_fixture(&[( + "session-distinct-collisions", + &format!("{first}\n{second}\n"), + )]); + let _env = env_scope(&[( + COPILOT_CONFIG_DIR_ENV, + Some(fixture.root().to_str().unwrap()), + )]); + + let mut args = shared_args_default(); + args.mode = CostMode::Auto; + let pricing = crate::PricingMap::default(); + let entries = load_entries_inner(&args, &pricing).unwrap(); + assert_eq!( + entries.len(), + 1, + "two credit-only rows with same model + naiu in same session \ + MUST collapse to one entry — this is the deliberate dedup \ + choice optimising for the real-data paired-snapshot shape; \ + see README 'Resumed sessions and dedup-key design'" + ); + assert!( + (entries[0].cost - 1.54481).abs() < 1e-9, + "expected single collapsed bill of $1.54481 (not $3.08962 if \ + event_id had been keyed), got {}", + entries[0].cost + ); + } + + #[test] + fn date_filter_runs_before_credit_only_dedup_collapse_to_preserve_in_range_row() { + // Regression: the credit-only dedup key + // (`credit-shutdown:{session}:{model}:{naiu}`) deliberately omits + // `event_id` so paired snapshots collapse (see the locking test + // above and README "Resumed sessions and dedup-key design"). The + // collapse is `HashMap::insert` last-wins by parse order. Before + // this fix, the `--since` / `--until` filter ran AFTER the + // dedup HashMap, so when two credit-only rows with the same + // `(session, model, naiu)` were parsed in the order + // [in-range, out-of-range], the HashMap kept the out-of-range + // (later-inserted) row and the subsequent date filter dropped it, + // silently losing the in-range row's credits entirely. The fix + // applies the filter to the `CopilotUsageEntry` vector BEFORE the + // dedup collapse, so each surviving entry already satisfies the + // date range and the collapse can never pick an out-of-range + // winner. This test pins the worst-case parse-order + // [in-range, out-of-range] inside a single events.jsonl file with + // `--until` cutting between the two timestamps; asserts the + // in-range row's credits survive. + let in_range = shutdown_with_credits_line( + "evt-in-range", + "2026-05-15T10:00:00.000Z", + "claude-opus-4.7-1m-internal", + 0, + 0, + 154_481_000_000, + 0, + ); + let out_of_range = shutdown_with_credits_line( + "evt-out-of-range", + "2026-05-20T10:00:00.000Z", + "claude-opus-4.7-1m-internal", + 0, + 0, + 154_481_000_000, // same naiu — would collide on credit-shutdown key + 0, + ); + // Parse order matters: in-range FIRST so the HashMap collapse + // would otherwise overwrite it with the out-of-range row. + let fixture = build_session_fixture(&[( + "session-date-filter-vs-credit-dedup", + &format!("{in_range}\n{out_of_range}\n"), + )]); + let _env = env_scope(&[( + COPILOT_CONFIG_DIR_ENV, + Some(fixture.root().to_str().unwrap()), + )]); + + let mut args = shared_args_default(); + args.mode = CostMode::Auto; + // Cut the date range so only the 2026-05-15 row qualifies. + // `SharedArgs::since` / `::until` are normalized to `YYYYMMDD` + // (no dashes) by the CLI parser; mirror that here. + args.since = Some("20260101".to_string()); + args.until = Some("20260516".to_string()); + // Use UTC so the test's RFC3339 timestamps map predictably to + // calendar dates regardless of the host timezone. + args.timezone = Some("UTC".to_string()); + let pricing = crate::PricingMap::default(); + let entries = load_entries_inner(&args, &pricing).unwrap(); + assert_eq!( + entries.len(), + 1, + "the in-range credit-only row MUST survive even though it \ + shares the content-based dedup key with an out-of-range row \ + parsed later in the same file. Pre-fix this returned 0 \ + entries (HashMap kept the later out-of-range row, then the \ + date filter dropped it). See README 'Resumed sessions and \ + dedup-key design'." + ); + assert!( + entries[0].date.starts_with("2026-05-15"), + "expected the in-range row (2026-05-15) to survive, got date {}", + entries[0].date, + ); + assert!( + (entries[0].cost - 1.54481).abs() < 1e-9, + "expected the in-range row's $1.54481 to survive intact, \ + got {}", + entries[0].cost, + ); + } + + #[test] + fn calculate_mode_uses_token_pricing_even_with_naiu_present() { + // Calculate / api always uses LiteLLM token pricing — the + // credit channel stays informational in JSON, but cost comes from + // the api-equivalent lookup. + let fixture = build_session_fixture(&[( + "session-calc-with-naiu", + &format!( + "{}\n", + shutdown_with_credits_line( + "evt-calc", + "2026-05-02T15:27:09.013Z", + "claude-opus-4.7-1m-internal", + 1_000, + 100, + 2_500_000_000, + 1, + ) + ), + )]); + let _env = env_scope(&[( + COPILOT_CONFIG_DIR_ENV, + Some(fixture.root().to_str().unwrap()), + )]); + + let mut pricing = crate::PricingMap::default(); + pricing.load_json( + r#"{"claude-opus-4-7":{"input_cost_per_token":0.0000015,"output_cost_per_token":0.0000075}}"#, + ); + let args = shared_args_default(); // mode = Calculate + let entries = load_entries_inner(&args, &pricing).unwrap(); + assert_eq!(entries.len(), 1); + let entry = &entries[0]; + // Cost from tokens, not credits. + assert!( + entry.cost > 0.0 && (entry.cost - 0.025).abs() > 1e-6, + "expected api-equivalent cost, got {} (credits would be 0.025)", + entry.cost + ); + // Credits channel still populated for the JSON / report layer. + assert_eq!(entry.credits, Some(2.5)); + } + + #[test] + fn calculate_mode_bills_zero_for_credit_only_zero_token_row() { + // A credit-only row (zero tokens, zero requests, non-zero AIU) + // under `--mode calculate` / `--mode api` should bill $0: there + // are no tokens to price, AIU is deliberately not consulted in + // calculate mode, and the row should NOT fall back to surfacing + // the credit-converted cost (that's `auto`/`display`'s job). + // The credits channel must still be exposed in JSON so callers + // who want the raw AIU count can still see it regardless of + // mode. + let fixture = build_session_fixture(&[( + "session-credit-only-calc", + &format!( + "{}\n", + shutdown_with_credits_line( + "evt-credit-only", + "2026-05-20T16:01:29.481Z", + "claude-opus-4.7-1m-internal", + 0, + 0, + 2_500_000_000, // 2.5 credits — would bill $0.025 in auto + 0, + ) + ), + )]); + let _env = env_scope(&[( + COPILOT_CONFIG_DIR_ENV, + Some(fixture.root().to_str().unwrap()), + )]); + + let mut pricing = crate::PricingMap::default(); + pricing.load_json( + r#"{"claude-opus-4-7":{"input_cost_per_token":0.0000015,"output_cost_per_token":0.0000075}}"#, + ); + let args = shared_args_default(); // mode = Calculate + let entries = load_entries_inner(&args, &pricing).unwrap(); + assert_eq!(entries.len(), 1); + let entry = &entries[0]; + // Zero tokens × any pricing = $0. + assert_eq!( + entry.cost, 0.0, + "calculate mode must bill $0 for a credit-only zero-token row; \ + got {} (auto would bill 0.025)", + entry.cost + ); + // Credits stay surfaced regardless of mode. + assert_eq!(entry.credits, Some(2.5)); + } + + #[test] + fn auto_mode_prefers_credits_when_aiu_is_present() { + // Auto is the user-facing default. For Copilot, the "true bill" is + // AI Credits whenever the source carries them — Auto must surface + // that, not the api-equivalent hypothetical. + let fixture = build_session_fixture(&[( + "session-auto-aiu", + &format!( + "{}\n", + shutdown_with_credits_line( + "evt-auto-aiu", + "2026-05-02T15:27:09.013Z", + "claude-opus-4.7-1m-internal", + 1_000, + 100, + 2_500_000_000, // 2.5 credits = $0.025 + 1, + ) + ), + )]); + let _env = env_scope(&[( + COPILOT_CONFIG_DIR_ENV, + Some(fixture.root().to_str().unwrap()), + )]); + + let mut args = shared_args_default(); + args.mode = CostMode::Auto; + // Token pricing is present but must be ignored when AIU is present. + let mut pricing = crate::PricingMap::default(); + pricing.load_json( + r#"{"claude-opus-4-7":{"input_cost_per_token":0.0000015,"output_cost_per_token":0.0000075}}"#, + ); + let entries = load_entries_inner(&args, &pricing).unwrap(); + assert_eq!(entries.len(), 1); + assert!( + (entries[0].cost - 0.025).abs() < 1e-9, + "Auto must prefer credits ($0.025), got ${}", + entries[0].cost + ); + } + + #[test] + fn auto_mode_uses_premium_request_billing_when_no_aiu_but_premium_requests_present() { + // Pre-cutover sessions (CLI < 1.0.40) have no `totalNanoAiu` but + // do ship `requests.cost`. Auto must surface the pre-cutover true + // bill: `requests.cost × $0.04`. This is closer to what GitHub + // actually charged the user than the LiteLLM-equivalent fallback. + let fixture = build_session_fixture(&[( + "session-pre-cutover", + &format!( + "{}\n", + json!({ + "type": "session.shutdown", + "id": "evt-pre", + "timestamp": "2026-04-15T09:52:27.352Z", + "data": {"modelMetrics": { + // Pre-cutover billable model: 3 requests at the + // Opus 4.6 multiplier (1×) = 3 premium requests. + "claude-opus-4.6": { + "usage": { + "inputTokens": 1_000u64, + "outputTokens": 100u64, + "cacheReadTokens": 0u64, + "cacheWriteTokens": 0u64, + "reasoningTokens": 0u64 + }, + "requests": {"count": 3, "cost": 3} + } + }} }) - .to_string(), + ), + )]); + let _env = env_scope(&[( + COPILOT_CONFIG_DIR_ENV, + Some(fixture.root().to_str().unwrap()), + )]); + + let mut args = shared_args_default(); + args.mode = CostMode::Auto; + let mut pricing = crate::PricingMap::default(); + pricing.load_json( + r#"{"claude-opus-4-6":{"input_cost_per_token":0.0000015,"output_cost_per_token":0.0000075}}"#, + ); + let entries = load_entries_inner(&args, &pricing).unwrap(); + assert_eq!(entries.len(), 1); + // 3 premium requests × $0.04 = $0.12. + assert!( + (entries[0].cost - 0.12).abs() < 1e-9, + "expected pre-cutover premium billing ($0.12), got {}", + entries[0].cost + ); + } + + #[test] + fn auto_mode_falls_through_to_token_pricing_when_cost_field_is_absent() { + // Forward-compat: if a future Copilot CLI ever stops emitting + // `requests.cost` while still reporting tokens and no AIU, Auto + // must fall through to LiteLLM token pricing rather than report + // a false `$0` bill from the premium-request branch. This is the + // loader-level counterpart to the parser regression test + // `absent_requests_cost_preserves_none_for_token_priced_fallback`. + let fixture = build_session_fixture(&[( + "session-absent-cost", + &format!( + "{}\n", json!({ - "hrTime": [1_775_934_263_u64, 0_u64], - "attributes": { - "event.name": "gen_ai.client.inference.operation.details", - "gen_ai.response.model": "gpt-5.4-mini", - "gen_ai.response.id": "resp-dupe", - "gen_ai.usage.input_tokens": 80, - "gen_ai.usage.output_tokens": 20, - }, - "_body": "GenAI inference: gpt-5.4-mini", + "type": "session.shutdown", + "id": "evt-absent-cost", + "timestamp": "2026-05-02T15:27:09.013Z", + "data": {"modelMetrics": { + "claude-opus-4.7": { + "usage": { + "inputTokens": 1_000u64, + "outputTokens": 100u64, + "cacheReadTokens": 0u64, + "cacheWriteTokens": 0u64, + "reasoningTokens": 0u64 + }, + // No `cost` field; no `totalNanoAiu`. Auto must + // not bill $0 — it must compute from tokens. + "requests": {"count": 1} + } + }} }) - .to_string(), + ), + )]); + let _env = env_scope(&[( + COPILOT_CONFIG_DIR_ENV, + Some(fixture.root().to_str().unwrap()), + )]); + + let mut args = shared_args_default(); + args.mode = CostMode::Auto; + let mut pricing = crate::PricingMap::default(); + pricing.load_json( + r#"{"claude-opus-4-7":{"input_cost_per_token":0.0000015,"output_cost_per_token":0.0000075}}"#, + ); + let entries = load_entries_inner(&args, &pricing).unwrap(); + assert_eq!(entries.len(), 1); + // 1000 input × $0.0000015 + 100 output × $0.0000075 = $0.0015 + $0.00075 = $0.00225 + assert!( + (entries[0].cost - 0.00225).abs() < 1e-9, + "Auto with absent `cost` field must fall through to token pricing ($0.00225), got {}", + entries[0].cost + ); + assert_eq!(entries[0].missing_pricing_model, None); + } + + #[test] + fn auto_mode_handles_fractional_premium_request_cost() { + // Real-data invariant (~2% of rows): `requests.cost` can be + // fractional — Opus 4.7 multiplies 1 request by 7.5. Auto must + // bill `7.5 × $0.04 = $0.30` end-to-end without losing + // fidelity. This is a loader-level regression for the same bug + // the parser test pins (`accepts_fractional_premium_request_cost`). + let fixture = build_session_fixture(&[( + "session-frac-cost", + &format!( + "{}\n", json!({ - "type": "span", - "traceId": "trace-dupe", - "spanId": "chat-1", - "name": "chat gpt-5.4-mini", - "attributes": { - "gen_ai.operation.name": "chat", - "gen_ai.response.model": "gpt-5.4-mini", - "gen_ai.conversation.id": "conv-dupe", - "gen_ai.response.id": "resp-dupe", - "gen_ai.usage.input_tokens": 60, - "gen_ai.usage.output_tokens": 10, - }, + "type": "session.shutdown", + "id": "evt-frac", + "timestamp": "2026-04-15T09:52:27.352Z", + "data": {"modelMetrics": { + "claude-opus-4.7": { + "usage": { + "inputTokens": 1_000u64, + "outputTokens": 100u64, + "cacheReadTokens": 0u64, + "cacheWriteTokens": 0u64, + "reasoningTokens": 0u64 + }, + "requests": {"count": 1, "cost": 7.5} + } + }} }) - .to_string(), - ] - .join("\n"), - }); - let file = fixture.path("copilot.jsonl"); + ), + )]); + let _env = env_scope(&[( + COPILOT_CONFIG_DIR_ENV, + Some(fixture.root().to_str().unwrap()), + )]); - let entries = parse_otel_file(&file).unwrap(); + let mut args = shared_args_default(); + args.mode = CostMode::Auto; + let pricing = crate::PricingMap::default(); + let entries = load_entries_inner(&args, &pricing).unwrap(); + assert_eq!(entries.len(), 1); + // 7.5 premium requests × $0.04 = $0.30 — without f64 parsing this + // would either round to $0.04 (cost=1) or drop the row entirely. + assert!( + (entries[0].cost - 0.30).abs() < 1e-9, + "expected fractional premium billing ($0.30), got {}", + entries[0].cost + ); + } + #[test] + fn auto_mode_some_zero_aiu_short_circuits_to_zero_over_nonzero_premium() { + // Pin the documented `has_aiu = credits.is_some()` semantics: a + // post-cutover row that explicitly reports `totalNanoAiu: 0` + // (genuine "AIU charged, value zero") alongside a non-zero + // `requests.cost` MUST bill `$0.00` via the AIU arm — NOT + // `cost × $0.04` via the premium arm. The `requests.cost` field is + // an inert legacy artifact on post-cutover sessions; treating + // `Some(0)` AIU as "AIU absent, fall through" would invent cost + // the user never owed. This is the one edge where the + // "presence, not value" dispatch framing diverges from intuition. + let fixture = build_session_fixture(&[( + "session-zero-aiu-with-cost", + &format!( + "{}\n", + json!({ + "type": "session.shutdown", + "id": "evt-zero-aiu-with-cost", + "timestamp": "2026-06-15T10:00:00.000Z", + "data": {"modelMetrics": { + "claude-opus-4.7": { + "usage": { + "inputTokens": 1_000u64, + "outputTokens": 100u64, + "cacheReadTokens": 0u64, + "cacheWriteTokens": 0u64, + "reasoningTokens": 0u64 + }, + "requests": {"count": 1, "cost": 4.0}, + "totalNanoAiu": 0u64 + } + }} + }) + ), + )]); + let _env = env_scope(&[( + COPILOT_CONFIG_DIR_ENV, + Some(fixture.root().to_str().unwrap()), + )]); + + let mut args = shared_args_default(); + args.mode = CostMode::Auto; + let pricing = crate::PricingMap::default(); + let entries = load_entries_inner(&args, &pricing).unwrap(); assert_eq!(entries.len(), 1); - assert_eq!(entries[0].dedup_key, "trace-dupe:chat-1"); - assert_eq!(entries[0].input_tokens, 60); - assert_eq!(entries[0].output_tokens, 10); + assert_eq!(entries[0].credits, Some(0.0)); + // Would be `4.0 × $0.04 = $0.16` if `Some(0)` AIU were treated as + // "AIU absent" and Auto fell through to the premium arm. The AIU + // arm wins because `credits.is_some()`. + assert_eq!( + entries[0].cost, 0.0, + "Some(0) AIU must short-circuit Auto to $0 over a non-zero premium cost", + ); } #[test] - fn includes_reasoning_tokens_in_total_tokens() { - let fixture = fs_fixture!({ - "copilot.jsonl": - format!( + fn auto_mode_uses_zero_for_pre_cutover_free_tier_rows() { + // Pre-cutover free-tier models (sonnet, haiku) report + // `requests.count > 0` but `requests.cost == 0` because they + // didn't burn premium-request allotment. Under the premium + // billing model the user genuinely paid $0 for these rows, so + // Auto must NOT fall through to token-priced fallback — that + // would invent cost the user never owed. + let fixture = build_session_fixture(&[( + "session-free-tier", + &format!( "{}\n", json!({ - "type": "span", - "traceId": "trace-1", - "spanId": "span-1", - "name": "chat test-model", - "endTime": [1_775_934_264_u64, 0_u64], - "attributes": { - "gen_ai.operation.name": "chat", - "gen_ai.response.model": "test-model", - "gen_ai.conversation.id": "conv-1", - "gen_ai.usage.input_tokens": 100, - "gen_ai.usage.output_tokens": 50, - "gen_ai.usage.cache_read.input_tokens": 10, - "gen_ai.usage.cache_creation.input_tokens": 20, - "gen_ai.usage.reasoning.output_tokens": 5, - }, + "type": "session.shutdown", + "id": "evt-free", + "timestamp": "2026-04-15T09:52:27.352Z", + "data": {"modelMetrics": { + "claude-sonnet-4.5": { + "usage": { + "inputTokens": 50_000u64, + "outputTokens": 5_000u64, + "cacheReadTokens": 10_000u64, + "cacheWriteTokens": 0u64, + "reasoningTokens": 0u64 + }, + "requests": {"count": 18, "cost": 0} + } + }} }) ), - }); - let file = fixture.path("copilot.jsonl"); + )]); + let _env = env_scope(&[( + COPILOT_CONFIG_DIR_ENV, + Some(fixture.root().to_str().unwrap()), + )]); + + let mut args = shared_args_default(); + args.mode = CostMode::Auto; let mut pricing = crate::PricingMap::default(); pricing.load_json( - r#"{"test-model":{"input_cost_per_token":1,"output_cost_per_token":2,"cache_creation_input_token_cost":3,"cache_read_input_token_cost":4}}"#, + r#"{"claude-sonnet-4-5":{"input_cost_per_token":0.000003,"output_cost_per_token":0.000015}}"#, + ); + let entries = load_entries_inner(&args, &pricing).unwrap(); + assert_eq!(entries.len(), 1); + // Premium-request cost is 0 → free-tier under the pre-cutover plan + // → bill $0 even though tokens were used. + assert_eq!( + entries[0].cost, 0.0, + "free-tier pre-cutover rows must bill $0 under premium model" ); + } - let loaded = read_otel_file(&file, None, CostMode::Auto, &pricing).unwrap(); - let rows = summarize_entries(&loaded, AgentReportKind::Daily).unwrap(); - let report = report_from_rows(&rows, AgentReportKind::Daily); + #[test] + fn display_mode_returns_credits_when_aiu_is_present() { + // Realigned semantics: Display = "show what the source precomputed". + // For Copilot, that's AIU when present (the same number Credits + // mode shows) — analogous to how Claude Display returns Anthropic's + // `costUSD`. + let fixture = build_session_fixture(&[( + "session-display", + &format!( + "{}\n", + shutdown_with_credits_line( + "evt-display", + "2026-05-02T15:27:09.013Z", + "claude-opus-4.7-1m-internal", + 1_000, + 100, + 2_500_000_000, + 1, + ) + ), + )]); + let _env = env_scope(&[( + COPILOT_CONFIG_DIR_ENV, + Some(fixture.root().to_str().unwrap()), + )]); - assert_eq!(report["daily"][0]["inputTokens"], 90); - assert_eq!(report["daily"][0]["outputTokens"], 50); - assert_eq!(report["daily"][0]["totalTokens"], 175); - assert_eq!(report["daily"][0]["totalCost"], 300.0); - assert_eq!( - report["daily"][0]["modelBreakdowns"], - json!([{ - "modelName": "test-model", - "inputTokens": 90, - "outputTokens": 50, - "cacheCreationTokens": 20, - "cacheReadTokens": 10, - "cost": 300.0 - }]) + let mut args = shared_args_default(); + args.mode = CostMode::Display; + let pricing = crate::PricingMap::default(); + let entries = load_entries_inner(&args, &pricing).unwrap(); + assert_eq!(entries.len(), 1); + assert!( + (entries[0].cost - 0.025).abs() < 1e-9, + "Display must surface AIU-derived cost, got ${}", + entries[0].cost ); } #[test] - fn falls_back_to_total_tokens_when_copilot_parts_are_missing() { - let fixture = fs_fixture!({ - "copilot.jsonl": - format!( + fn display_mode_surfaces_premium_request_cost_when_aiu_is_absent() { + // Display walks the true-bill ladder: AIU first, then premium + // requests, then $0. For pre-cutover data without AIU, that means + // surfacing the premium-request cost the source already shipped + // (no token-priced fallback in Display mode). + let fixture = build_session_fixture(&[( + "session-pre-display", + &format!( "{}\n", json!({ - "type": "span", - "traceId": "trace-1", - "spanId": "span-1", - "name": "chat test-model", - "endTime": [1_775_934_264_u64, 0_u64], - "attributes": { - "gen_ai.operation.name": "chat", - "gen_ai.response.model": "test-model", - "gen_ai.conversation.id": "conv-1", - "gen_ai.usage.total_tokens": 567, - }, + "type": "session.shutdown", + "id": "evt-pre-display", + "timestamp": "2026-04-15T09:52:27.352Z", + "data": {"modelMetrics": { + "claude-opus-4.7": { + "usage": { + "inputTokens": 1_000u64, + "outputTokens": 100u64, + "cacheReadTokens": 0u64, + "cacheWriteTokens": 0u64, + "reasoningTokens": 0u64 + }, + // 1 request × 7.5 multiplier = 7.5 premium + "requests": {"count": 1, "cost": 7.5} + } + }} }) ), - }); - let file = fixture.path("copilot.jsonl"); + )]); + let _env = env_scope(&[( + COPILOT_CONFIG_DIR_ENV, + Some(fixture.root().to_str().unwrap()), + )]); - let entries = parse_otel_file(&file).unwrap(); + let mut args = shared_args_default(); + args.mode = CostMode::Display; + let pricing = crate::PricingMap::default(); + let entries = load_entries_inner(&args, &pricing).unwrap(); + assert_eq!(entries.len(), 1); + // 7.5 × $0.04 = $0.30. + assert!( + (entries[0].cost - 0.30).abs() < 1e-9, + "Display must surface premium-request cost when AIU absent, got ${}", + entries[0].cost + ); + } + + #[test] + fn auto_mode_aggregate_only_synthetic_entry_bills_from_credits() { + // Forward-compat: when only data.totalNanoAiu is present (not in + // current local real data), Auto still bills the aggregate. + let fixture = build_session_fixture(&[( + "session-agg", + &format!( + "{}\n", + json!({ + "type": "session.shutdown", + "id": "evt-agg", + "timestamp": "2026-05-20T16:01:29.481Z", + "data": { + "modelMetrics": {}, + "totalNanoAiu": 5_000_000_000u64 + } + }) + ), + )]); + let _env = env_scope(&[( + COPILOT_CONFIG_DIR_ENV, + Some(fixture.root().to_str().unwrap()), + )]); + let mut args = shared_args_default(); + args.mode = CostMode::Auto; + let pricing = crate::PricingMap::default(); + let entries = load_entries_inner(&args, &pricing).unwrap(); assert_eq!(entries.len(), 1); - assert_eq!(entries[0].output_tokens, 567); - assert_eq!(entries[0].reasoning_output_tokens, 0); + assert!((entries[0].cost - 0.05).abs() < 1e-9); + // Synthetic entry — no model assigned. + assert!(entries[0].model.is_none()); + } + + #[test] + #[cfg(unix)] + fn one_unreadable_session_file_does_not_abort_whole_report() { + // Per-file error isolation: one bad/locked/corrupted session-state + // file MUST NOT abort the whole report. Other ccusage adapters + // treat parse errors as per-file skips; the same semantic must + // hold here. A locked file (Windows, antivirus scanning), a + // partial write from a still-running CLI, or one file with + // permission errors shouldn't make `ccusage copilot daily` print + // zero — it should report whatever the OTHER sessions show. + // + // Hermetic: build a fixture with TWO session directories. The + // first is a real, readable shutdown event ($0.04 under Auto). + // The second is a real `events.jsonl` file whose POSIX mode is + // `0o000` — `is_file()` returns true (so path discovery + // enumerates it) but `fs::File::open` returns + // `PermissionDenied`. This routes through the new + // `match parse_session_state_file(...) { Err(_) => skip }` arm + // in `load_entries_inner` rather than being filtered upstream. + // + // CAUTION: an earlier version of this test created a *directory* + // at the events.jsonl position. That fixture was vacuous: a + // directory fails `is_file()`, so path discovery silently drops + // it before the loader ever opens anything — the test would + // pass even when the production fix was reverted. EISDIR alone + // does NOT reach the loader. The chmod-0o000 trigger here does, + // and the test fails deterministically against the buggy + // pre-fix code (`entries.extend(parse_session_state_file(&path)?)`). + use std::os::unix::fs::PermissionsExt; + let fixture = ccusage_test_support::Fixture::new(); + let _ = fixture.write_file( + "session-state/good-uuid/events.jsonl", + format!( + "{}\n", + json!({ + "type": "session.shutdown", + "id": "evt-good", + "timestamp": "2026-04-15T09:52:27.352Z", + "data": {"modelMetrics": { + "claude-opus-4.7": { + "usage": { + "inputTokens": 1_000u64, + "outputTokens": 100u64, + "cacheReadTokens": 0u64, + "cacheWriteTokens": 0u64, + "reasoningTokens": 0u64 + }, + "requests": {"count": 1, "cost": 1} + } + }} + }) + ), + ); + // Write events.jsonl as a real file (so `is_file()` lets path + // discovery enumerate it), then strip all permissions so + // `File::open` returns `PermissionDenied` — the real io error + // class the loader's `match` arm must isolate. + let bad_file = fixture.write_file( + "session-state/bad-uuid/events.jsonl", + "{\"this content should never be read; mode is 0o000\"}\n", + ); + std::fs::set_permissions(&bad_file, std::fs::Permissions::from_mode(0o000)) + .expect("chmod 0o000 on bad-file fixture"); + + let _env = env_scope(&[( + COPILOT_CONFIG_DIR_ENV, + Some(fixture.root().to_str().unwrap()), + )]); + + let mut args = shared_args_default(); + args.mode = CostMode::Auto; + let pricing = crate::PricingMap::default(); + // Critical assertion: the call must succeed (Ok), not propagate + // the bad-file error. Before the fix this would return Err. + let result = load_entries_inner(&args, &pricing); + + // Restore permissions BEFORE any assertion can panic, so the + // tempdir cleanup at fixture drop can remove the file. Without + // this, a failing assertion leaves a 0o000 file that prevents + // TempDir from rmdir-ing the parent. + let _ = std::fs::set_permissions(&bad_file, std::fs::Permissions::from_mode(0o644)); + + let entries = result.expect("loader must succeed despite the bad file"); + // The good file's one entry must survive — the bad file's read + // error was isolated and warned about (stderr, not part of the + // returned Vec). + assert_eq!( + entries.len(), + 1, + "good-file entry must survive bad-file read error; got {entries:?}" + ); + // 1 premium request × $0.04 = $0.04 + assert!( + (entries[0].cost - 0.04).abs() < 1e-9, + "expected $0.04 from the good file, got {}", + entries[0].cost + ); } } diff --git a/rust/crates/ccusage/src/adapter/copilot/mod.rs b/rust/crates/ccusage/src/adapter/copilot/mod.rs index bb2415b..7e9e60f 100644 --- a/rust/crates/ccusage/src/adapter/copilot/mod.rs +++ b/rust/crates/ccusage/src/adapter/copilot/mod.rs @@ -3,6 +3,8 @@ mod parser; mod paths; mod report; +use std::sync::OnceLock; + use crate::cli::AgentCommandArgs; use crate::{ PricingMap, Result, filter_loaded_entries_by_date, print_json_or_jq, print_usage_table, @@ -10,8 +12,29 @@ use crate::{ }; pub(crate) use loader::load_entries; +#[cfg(test)] +pub(crate) use paths::COPILOT_CONFIG_DIR_ENV; pub(crate) use report::{report_from_rows, summarize_entries}; +/// Returns `true` if any GitHub Copilot session-state file exists on disk +/// (under `/session-state//events.jsonl`), +/// regardless of whether parsing succeeds or whether the active +/// `--since`/`--until` filter excludes every entry. +/// +/// Used by the cross-source aggregator (`adapter::all::loader::load_copilot_rows`) +/// to keep "copilot" in the `Detected:` report header even when the date +/// filter narrows the row set to empty — mirroring the +/// `qwen::has_data()` sentinel pattern. This is required because +/// `load_entries_inner` pre-filters by date before its content-keyed dedup +/// HashMap collapse (see `loader.rs` — the credit-only dedup key omits +/// `event_id`, so filtering after the HashMap could let a content-key +/// collision drop the in-range row). With the pre-filter in place, +/// `!entries.is_empty()` no longer reflects on-disk presence; the +/// `has_data()` sentinel restores that signal. +pub(crate) fn has_data() -> bool { + paths::has_any_session_state_event_file() +} + pub(crate) fn run(args: AgentCommandArgs) -> Result<()> { let shared = args.shared; let pricing = PricingMap::load_with_overrides( @@ -19,6 +42,13 @@ pub(crate) fn run(args: AgentCommandArgs) -> Result<()> { crate::log_level() != Some(0), shared.pricing_overrides.iter(), ); + // `load_entries` triggers `warn_about_inert_legacy_env_vars_once` + // internally, so direct `ccusage copilot ...` and the cross-source + // aggregator (`ccusage daily --all`) both surface the warning via the + // same code path. The `OnceLock` inside that helper keeps the warning + // to a single emission per process — including the case where both + // direct invocation and the aggregator run in the same process (they + // don't today, but the gate is cheap insurance). let mut entries = load_entries(&shared, &pricing)?; filter_loaded_entries_by_date(&mut entries, &shared); let mut rows = summarize_entries(&entries, args.kind)?; @@ -47,8 +77,58 @@ pub(crate) fn run(args: AgentCommandArgs) -> Result<()> { Ok(()) } +/// Process-wide OnceLock that guards the legacy-OTel-env-var deprecation +/// warning. Initialized on first call; subsequent calls are no-ops. This is +/// what keeps the warning at most one emission per process even when +/// `load_entries` is hit through both `copilot::run` and the +/// cross-source `all` aggregator. +static LEGACY_OTEL_WARNING_EMITTED: OnceLock<()> = OnceLock::new(); + +/// Emit a one-shot warning to stderr when the user still has any of the +/// legacy OTel environment variables set. ccusage no longer reads OTel +/// exports (the production loader uses `~/.copilot/session-state/` directly), +/// so silently ignoring `COPILOT_OTEL_FILE_EXPORTER_PATH` / `COPILOT_OTEL_DEDUP` +/// / `COPILOT_PREFER_OTEL` would surprise users who configured them on a +/// previous ccusage version. Routed through the same `log_level`-aware +/// gate as the rest of the warning surface so `LOG_LEVEL=0` silences it. +/// +/// Called from `copilot::load_entries` (NOT only from `copilot::run`) so +/// the warning ALSO fires when Copilot is loaded indirectly via the +/// cross-source aggregator (`ccusage daily --all`). The process-wide +/// `OnceLock` ensures at most one emission per process. +pub(crate) fn warn_about_inert_legacy_env_vars_once() { + // Order matters: check the guards BEFORE consuming the OnceLock, so + // the one-shot is only burned when we actually emit a warning. If we + // set the lock first (the obvious order), the first `load_entries` + // of the process always consumes it — even with no legacy vars set — + // and a later invocation that genuinely has the env vars set would be + // silently suppressed. (Pure polish today since env vars are constant + // within a process, but the name promises "warn-once" not + // "called-once.") + if crate::log_level() == Some(0) { + return; + } + let in_use = paths::legacy_otel_env_vars_in_use(); + if in_use.is_empty() { + return; + } + if LEGACY_OTEL_WARNING_EMITTED.set(()).is_err() { + return; + } + eprintln!( + "warning: ccusage no longer reads OpenTelemetry exports; the following \ + environment variable{plural} {verb} ignored: {names}. ccusage now reads \ + ~/.copilot/session-state//events.jsonl by default. \ + Unset these to silence this warning. See \ + https://ccusage.com/guide/copilot/#data-source", + plural = if in_use.len() == 1 { "" } else { "s" }, + verb = if in_use.len() == 1 { "is" } else { "are" }, + names = in_use.join(", "), + ); +} + fn empty_usage_message() -> &'static str { - "No GitHub Copilot CLI usage data found.\nEnable Copilot OpenTelemetry file export before starting or resuming Copilot sessions.\nSee https://ccusage.com/guide/copilot/#data-source" + "No GitHub Copilot CLI usage data found.\nThe Copilot CLI writes per-session events to ~/.copilot/session-state//events.jsonl; verify Copilot CLI is installed and has at least one shutdown record. Override the base directory with COPILOT_CONFIG_DIR if your install lives elsewhere.\nSee https://ccusage.com/guide/copilot/#data-source" } #[cfg(test)] @@ -60,4 +140,17 @@ mod tests { let message = empty_usage_message(); assert!(message.contains("https://ccusage.com/guide/copilot/#data-source")); } + + #[test] + fn empty_usage_message_recommends_session_state() { + let message = empty_usage_message(); + assert!( + message.contains("session-state"), + "session-state must be mentioned: {message}" + ); + assert!( + !message.contains("OTel") && !message.contains("OpenTelemetry"), + "OTel must no longer be recommended in the empty-state message: {message}" + ); + } } diff --git a/rust/crates/ccusage/src/adapter/copilot/parser.rs b/rust/crates/ccusage/src/adapter/copilot/parser.rs index 496db47..d68b454 100644 --- a/rust/crates/ccusage/src/adapter/copilot/parser.rs +++ b/rust/crates/ccusage/src/adapter/copilot/parser.rs @@ -1,53 +1,13 @@ use std::{ - collections::{HashMap, HashSet}, + collections::HashMap, fs, + io::{BufRead, BufReader}, path::Path, }; -use serde::Deserialize; -use serde_json::{Map, Value}; +use serde_json::Value; -use super::super::jsonl; -use crate::{Result, TimestampMs, TokenUsageRaw, apply_total_token_fallback, fast::LinePrefilter}; - -/// A single parsed Copilot OpenTelemetry record. Only the fields ccusage -/// consumes are declared; serde skips everything else. The `attributes` block -/// is kept as a dynamic map because Copilot addresses it by arbitrary dotted -/// keys (for example `gen_ai.usage.input_tokens`), and the timestamp-bearing -/// fields stay as raw values because they appear as both numeric scalars and -/// `[seconds, nanos]` arrays depending on the exporter. -#[derive(Debug, Deserialize)] -struct CopilotRecord { - #[serde(rename = "type")] - record_type: Option, - name: Option, - #[serde(rename = "spanId")] - span_id: Option, - #[serde(rename = "traceId")] - trace_id: Option, - #[serde(rename = "spanContext")] - span_context: Option, - #[serde(rename = "startTime")] - start_time: Option, - #[serde(rename = "endTime")] - end_time: Option, - duration: Option, - kind: Option, - #[serde(rename = "hrTime")] - hr_time: Option, - #[serde(rename = "_hrTime")] - underscore_hr_time: Option, - time: Option, - timestamp: Option, - #[serde(rename = "observedTimestamp")] - observed_timestamp: Option, - #[serde(rename = "timeUnixNano")] - time_unix_nano: Option, - body: Option, - #[serde(rename = "_body")] - underscore_body: Option, - attributes: Option>, -} +use crate::{Result, TimestampMs}; #[derive(Debug, Clone)] pub(super) struct CopilotUsageEntry { @@ -61,466 +21,1939 @@ pub(super) struct CopilotUsageEntry { pub(super) cache_read_tokens: u64, pub(super) reasoning_output_tokens: u64, pub(super) dedup_key: String, + /// AI Credits in `nanoAiu` (10⁻⁹ AI Units) when the Copilot CLI reported + /// them on the source event. `None` for session-state shutdowns that + /// predate the AI Credits schema (CLI versions before ~1.0.40). + pub(super) nano_aiu: Option, + /// Number of premium requests this row consumed under the pre-June-2026 + /// billing model. The Copilot CLI bakes per-model multipliers into this + /// value (e.g. Opus 4.7 with 1 request × 7.5 multiplier = 7.5 premium + /// requests). Fractional in real data, hence `f64`. + /// + /// `None` in any of: + /// * The synthetic aggregate-credit entry (no source model or request + /// data to attribute). + /// * A session-state row whose source omits the `cost` field entirely + /// (today unreachable — every observed row ships the field — but + /// forward-compat against a future Copilot CLI that might drop it, + /// in which case Auto's dispatch falls through to token-priced + /// pricing rather than reporting a false `$0` bill). + /// + /// `Some(0.0)` is reserved for free-tier models (sonnet, haiku) under + /// the premium-request plan where the field is explicitly zero. + /// + /// Used by `auto`/`display` mode as the pre-AIU fallback before + /// token-priced cost. + pub(super) premium_request_cost: Option, +} + +// ------------------------------------------------------------------------- +// session-state parser (`~/.copilot/session-state//events.jsonl`) +// ------------------------------------------------------------------------- + +fn file_modified_timestamp(path: &Path) -> TimestampMs { + fs::metadata(path) + .and_then(|metadata| metadata.modified()) + .ok() + .and_then(|modified| modified.duration_since(std::time::UNIX_EPOCH).ok()) + .map(|duration| TimestampMs::from_millis(duration.as_millis().min(i64::MAX as u128) as i64)) + .unwrap_or_else(crate::utc_now) } -#[derive(Debug, Clone, Copy, Eq, PartialEq)] -enum CopilotUsageSource { - ChatSpan, - InferenceLog, - AgentTurnLog, - AgentSummarySpan, +// `SESSION_SHUTDOWN_TYPE` serves two roles in the parse pipeline: +// +// 1. Substring needle: `str::contains(SESSION_SHUTDOWN_TYPE)` runs on +// the raw JSON line text BEFORE serde parsing, as a cheap pre-filter +// that lets non-shutdown lines short-circuit without paying for a +// full `from_str::`. +// 2. Exact-match: compared against the parsed `ShutdownEvent.event_type` +// field AFTER serde, to defend against other event kinds (e.g. +// `tool.execution_start`) whose `arguments.command` payload happens +// to contain the substring "session.shutdown". +// +// One const used for both roles can't desync. If a future Copilot CLI +// schema renames the event type (e.g. to "session.exit"), updating this +// single literal flips both the pre-filter AND the exact-match together. +const SESSION_SHUTDOWN_TYPE: &str = "session.shutdown"; +const GEMINI_PREFIX: &str = "gemini-"; + +#[derive(serde::Deserialize)] +#[serde(rename_all = "camelCase")] +struct ShutdownEvent { + // Folding the discriminator into the main struct avoids re-parsing + // each line as a `TypeOnly`-shaped second pass (one of the hot loops + // in `parse_session_state_file`). The substring filter on + // `SESSION_SHUTDOWN_TYPE` still runs first to skip non-shutdown + // lines without any serde work; this field is the authoritative + // type check that defends against other event types whose + // arguments/content happen to contain the literal substring + // "session.shutdown". + #[serde(rename = "type")] + event_type: String, + id: String, + timestamp: String, + #[serde(default)] + data: ShutdownData, } -#[derive(Default)] -struct TraceContext { - model: Option, - session_id: Option, - session_id_priority: u8, +#[derive(serde::Deserialize, Default)] +#[serde(rename_all = "camelCase")] +struct ShutdownData { + #[serde(default)] + model_metrics: HashMap, + // `total_nano_aiu` (and its per-model sibling on `ModelMetrics`) is typed + // as `u64` because "nano" units are integer by definition — there's no + // meaningful fractional nano-AIU. To stay forward-compatible against a + // future Copilot CLI that emits the field as a JSON float (e.g. + // `1.5e11` or `100000000000.0`), the custom deserializer + // `deserialize_nano_aiu` accepts BOTH integer and float JSON forms and + // truncates floats to `u64`. Without this, a float-valued shutdown + // would fail the whole `ShutdownEvent` deserialize and drop every + // model in that shutdown — the exact failure class fixed for + // `requests.cost` (which IS legitimately fractional). + #[serde(default, deserialize_with = "deserialize_nano_aiu")] + total_nano_aiu: Option, } -struct CopilotUsageCandidate { - source: CopilotUsageSource, - trace_id: Option, - response_id: Option, - model: String, - session_id: String, - timestamp: TimestampMs, +#[derive(serde::Deserialize, Default)] +#[serde(rename_all = "camelCase")] +struct ModelMetrics { + #[serde(default)] + usage: SessionUsage, + #[serde(default)] + requests: SessionRequests, + // See the `total_nano_aiu` note on `ShutdownData` above for why this + // is `u64` rather than `f64`, and why both forms are accepted. + #[serde(default, deserialize_with = "deserialize_nano_aiu")] + total_nano_aiu: Option, +} + +/// Tolerant deserializer for `totalNanoAiu` that accepts both JSON integer +/// (the only form observed in the local 200-file corpus) and JSON float +/// (a forward-compat shape a future Copilot CLI release could emit). Floats +/// are truncated to `u64`; negative values, NaN, and overflow are rejected +/// with a `serde` error rather than silently coerced. +/// +/// Pinned by `tolerates_float_valued_per_model_total_nano_aiu`, +/// `tolerates_float_valued_aggregate_total_nano_aiu`, and +/// `rejects_negative_float_total_nano_aiu`. +fn deserialize_nano_aiu<'de, D>(deserializer: D) -> std::result::Result, D::Error> +where + D: serde::Deserializer<'de>, +{ + use serde::Deserialize; + use serde::de::{Error, Unexpected}; + let value = Option::::deserialize(deserializer)?; + match value { + None | Some(Value::Null) => Ok(None), + Some(Value::Number(n)) => { + if let Some(u) = n.as_u64() { + Ok(Some(u)) + } else if let Some(f) = n.as_f64() { + if !f.is_finite() || f < 0.0 { + Err(D::Error::invalid_value( + Unexpected::Float(f), + &"a non-negative finite number for nano-AIU", + )) + } else if f >= (u64::MAX as f64) { + Err(D::Error::invalid_value( + Unexpected::Float(f), + &"a nano-AIU value that fits in u64", + )) + } else { + Ok(Some(f as u64)) + } + } else { + Err(D::Error::custom(format!( + "nano-AIU number not representable as u64 or f64: {n}" + ))) + } + } + Some(other) => Err(D::Error::custom(format!( + "nano-AIU must be a number, got {}", + describe_value(&other), + ))), + } +} + +fn describe_value(value: &Value) -> &'static str { + match value { + Value::Null => "null", + Value::Bool(_) => "bool", + Value::Number(_) => "number", + Value::String(_) => "string", + Value::Array(_) => "array", + Value::Object(_) => "object", + } +} + +#[derive(serde::Deserialize, Default)] +#[serde(rename_all = "camelCase")] +struct SessionUsage { + #[serde(default)] input_tokens: u64, + #[serde(default)] output_tokens: u64, - cache_creation_tokens: u64, + #[serde(default)] cache_read_tokens: u64, - reasoning_output_tokens: u64, - dedup_key: String, + #[serde(default)] + cache_write_tokens: u64, + #[serde(default)] + reasoning_tokens: u64, } -pub(super) fn parse_otel_file(path: &Path) -> Result> { - let content = fs::read(path)?; - // Every usable Copilot OTel record carries the `attributes` object, so - // lines without it are skipped before JSON parsing. - let prefilter = LinePrefilter::all(&[br#""attributes""#]); - let records = jsonl::records::(&content, Some(&prefilter)).collect::>(); - let trace_contexts = collect_trace_contexts(&records); - let fallback_timestamp = file_modified_timestamp(path); - let candidates = records - .iter() - .enumerate() - .filter_map(|(index, record)| { - to_candidate(record, index, fallback_timestamp, &trace_contexts) - }) - .collect::>(); - let sets = CandidateSets::new(&candidates); - Ok(candidates - .into_iter() - .filter(|candidate| should_emit_candidate(candidate, &sets)) - .map(|candidate| CopilotUsageEntry { - timestamp: candidate.timestamp, - timestamp_text: crate::format_rfc3339_millis(candidate.timestamp), - session_id: candidate.session_id, - model: candidate.model, - input_tokens: candidate.input_tokens, - output_tokens: candidate.output_tokens, - cache_creation_tokens: candidate.cache_creation_tokens, - cache_read_tokens: candidate.cache_read_tokens, - reasoning_output_tokens: candidate.reasoning_output_tokens, - dedup_key: candidate.dedup_key, - }) - .collect()) +#[derive(serde::Deserialize, Default)] +#[serde(rename_all = "camelCase")] +struct SessionRequests { + #[serde(default)] + count: u64, + // Fractional premium-request count; `None` means Auto falls back to + // token pricing instead of inventing a false `$0` source bill. + #[serde(default, deserialize_with = "deserialize_premium_request_cost")] + cost: Option, +} + +/// Tolerant deserializer for `requests.cost` that matches +/// [`deserialize_nano_aiu`]: accepts integer/float JSON forms and rejects +/// non-finite or negative values. +fn deserialize_premium_request_cost<'de, D>( + deserializer: D, +) -> std::result::Result, D::Error> +where + D: serde::Deserializer<'de>, +{ + use serde::Deserialize; + use serde::de::{Error, Unexpected}; + let value = Option::::deserialize(deserializer)?; + match value { + None | Some(Value::Null) => Ok(None), + Some(Value::Number(n)) => { + if let Some(u) = n.as_u64() { + Ok(Some(u as f64)) + } else if let Some(f) = n.as_f64() { + if !f.is_finite() { + Err(D::Error::invalid_value( + Unexpected::Float(f), + &"a finite (non-NaN, non-Infinity) number for requests.cost", + )) + } else if f < 0.0 { + Err(D::Error::invalid_value( + Unexpected::Float(f), + &"a non-negative number for requests.cost", + )) + } else { + Ok(Some(f)) + } + } else { + Err(D::Error::custom(format!( + "requests.cost number not representable as u64 or f64: {n}" + ))) + } + } + Some(other) => Err(D::Error::custom(format!( + "requests.cost must be a number, got {}", + describe_value(&other), + ))), + } } -fn collect_trace_contexts(records: &[CopilotRecord]) -> HashMap { - let mut contexts = HashMap::new(); - for record in records { - let Some(trace_id) = trace_id_from_record(record) else { +pub(super) fn parse_session_state_file(path: &Path) -> Result> { + // Stream the file via `BufReader::split(b'\n')` rather than + // `fs::read` so peak memory stays bounded by line size (a few KB) and + // not file size. Real-world `events.jsonl` files reach 69MB+ for + // heavy users, where the one-shot read would briefly allocate a + // whole-file `Vec` per session-state file. Byte-level splitting + // (rather than `.lines()`) preserves the existing + // tolerate-invalid-UTF-8 / tolerate-truncated-trailing-line semantics. + let file = fs::File::open(path)?; + let reader = BufReader::new(file); + let session_id = session_id_from_path(path).unwrap_or_else(|| "unknown-session".to_string()); + // Computed lazily ONCE per file (not per row): the only consumer is + // the unparseable-timestamp fallback below, and real RFC3339 strings + // from the Copilot CLI always parse — so this is effectively never + // hit on observed data. Pre-computing it would do one fs::metadata + // syscall per file regardless of whether the fallback fires; an + // upfront syscall every parse_session_state_file call would be + // wasteful given the volume of files the loader walks. The + // `OnceCell` collapses to the upstream cost only on first need. + let fallback_timestamp: std::cell::OnceCell = std::cell::OnceCell::new(); + + let mut entries = Vec::new(); + for line_result in reader.split(b'\n') { + let line_bytes = line_result?; + let trimmed: &[u8] = match line_bytes.iter().position(|&b| !b.is_ascii_whitespace()) { + Some(start) => &line_bytes[start..], + None => continue, + }; + if trimmed.is_empty() { + continue; + } + let Ok(line_str) = std::str::from_utf8(trimmed) else { continue; }; - let Some(attributes) = record.attributes.as_ref() else { + if !line_str.contains(SESSION_SHUTDOWN_TYPE) { + continue; + } + let Ok(event) = serde_json::from_str::(line_str) else { continue; }; - let context = contexts - .entry(trace_id) - .or_insert_with(TraceContext::default); - if context.model.is_none() { - context.model = first_non_empty_attr(attributes, MODEL_ATTRS); + if event.event_type != SESSION_SHUTDOWN_TYPE { + continue; + } + let timestamp = crate::date_utils::parse_ts_timestamp(&event.timestamp) + .unwrap_or_else(|| *fallback_timestamp.get_or_init(|| file_modified_timestamp(path))); + + for (model, metrics) in &event.data.model_metrics { + if skip_metrics_row(model, metrics) { + continue; + } + entries.push(build_session_state_entry( + &event.id, + &session_id, + model, + metrics, + timestamp, + )); } - if let Some((session_id, priority)) = best_session_attr(attributes) - && priority > context.session_id_priority + + let any_per_model_priced_billing = event.data.model_metrics.iter().any(|(model, m)| { + !skip_metrics_row(model, m) + && (m.total_nano_aiu.is_some_and(|n| n > 0) + || m.requests.cost.is_some_and(|c| c > 0.0)) + }); + if let Some(naiu) = event + .data + .total_nano_aiu + .filter(|&naiu| naiu > 0 && !any_per_model_priced_billing) { - context.session_id = Some(session_id); - context.session_id_priority = priority; + entries.push(build_aggregate_credit_entry(&session_id, naiu, timestamp)); } } - contexts + Ok(entries) +} + +/// Skip all-empty rows, except nonzero AIU credit rows and Gemini reasoning-only rows. +fn skip_metrics_row(model: &str, metrics: &ModelMetrics) -> bool { + let usage = &metrics.usage; + let reasoning_counts_as_usage = model.starts_with(GEMINI_PREFIX); + let no_tokens = usage.input_tokens == 0 + && usage.output_tokens == 0 + && usage.cache_read_tokens == 0 + && usage.cache_write_tokens == 0 + && (!reasoning_counts_as_usage || usage.reasoning_tokens == 0); + let no_requests = metrics.requests.count == 0; + let no_credits = metrics.total_nano_aiu.is_none_or(|n| n == 0); + no_tokens && no_requests && no_credits } -fn to_candidate( - record: &CopilotRecord, - index: usize, - fallback_timestamp: TimestampMs, - trace_contexts: &HashMap, -) -> Option { - let attributes = record.attributes.as_ref()?; - let source = if is_chat_span_record(record, attributes) { - CopilotUsageSource::ChatSpan - } else if is_inference_log_record(record, attributes) { - CopilotUsageSource::InferenceLog - } else if is_agent_turn_log_record(record, attributes) { - CopilotUsageSource::AgentTurnLog - } else if is_agent_summary_span_record(record, attributes) { - CopilotUsageSource::AgentSummarySpan +fn build_session_state_entry( + event_id: &str, + session_id: &str, + model: &str, + metrics: &ModelMetrics, + timestamp: TimestampMs, +) -> CopilotUsageEntry { + let usage = &metrics.usage; + // inputTokens includes cache buckets; subtract them for fresh input. + let input_only = usage + .input_tokens + .saturating_sub(usage.cache_read_tokens) + .saturating_sub(usage.cache_write_tokens); + + // Only Gemini keeps reasoning separate; others include it in outputTokens. + let reasoning_output_tokens = if model.starts_with(GEMINI_PREFIX) { + usage.reasoning_tokens } else { - return None; + 0 }; - let input = attr_number(attributes, "gen_ai.usage.input_tokens"); - let output = attr_number(attributes, "gen_ai.usage.output_tokens"); - let cache_read = attr_number(attributes, "gen_ai.usage.cache_read.input_tokens"); - let cache_creation = attr_number_first( - attributes, - &[ - "gen_ai.usage.cache_write.input_tokens", - "gen_ai.usage.cache_creation.input_tokens", - ], - ); - let reasoning = attr_number_first( - attributes, - &[ - "gen_ai.usage.reasoning.output_tokens", - "gen_ai.usage.reasoning_tokens", - ], - ); - let total = attr_number_first( - attributes, - &[ - "gen_ai.usage.total_tokens", - "gen_ai.usage.total.token_count", - ], - ); - let usage = TokenUsageRaw { - input_tokens: input.saturating_sub(input.min(cache_read)), - output_tokens: output, - cache_creation_input_tokens: cache_creation, - cache_read_input_tokens: cache_read, - speed: None, - cache_creation: None, + + let zero_token = input_only == 0 + && usage.output_tokens == 0 + && usage.cache_read_tokens == 0 + && usage.cache_write_tokens == 0 + && reasoning_output_tokens == 0; + let credit_only = zero_token && metrics.requests.count == 0; + + let dedup_key = match (credit_only, metrics.total_nano_aiu) { + (true, Some(naiu)) => { + format!("credit-shutdown:{session_id}:{model}:{naiu}") + } + _ => format!("shutdown:{session_id}:{event_id}:{model}"), }; - let (usage, reasoning) = apply_total_token_fallback(usage, reasoning, total); - if crate::total_usage_tokens(usage) + reasoning == 0 { - return None; - } - let trace_id = trace_id_from_record(record); - let trace_context = trace_id.as_ref().and_then(|id| trace_contexts.get(id)); - let response_id = attr_string(attributes, "gen_ai.response.id"); - let model = first_non_empty_attr(attributes, MODEL_ATTRS) - .or_else(|| trace_context.and_then(|context| context.model.clone())) - .unwrap_or_else(|| "unknown".to_string()); - let session_id = best_session_attr(attributes) - .map(|(session_id, _)| session_id) - .or_else(|| trace_context.and_then(|context| context.session_id.clone())) - .or_else(|| trace_id.clone()) - .unwrap_or_else(|| "unknown-session".to_string()); - let timestamp = timestamp_from_record(record).unwrap_or(fallback_timestamp); - let dedup_key = dedup_key_for_record( - source, - record, - attributes, - &trace_id, - &session_id, - timestamp, - index, - ); - Some(CopilotUsageCandidate { - source, - trace_id, - response_id, - model, - session_id, + + CopilotUsageEntry { timestamp, - input_tokens: usage.input_tokens, + timestamp_text: crate::format_rfc3339_millis(timestamp), + session_id: session_id.to_string(), + model: model.to_string(), + input_tokens: input_only, output_tokens: usage.output_tokens, - cache_creation_tokens: usage.cache_creation_input_tokens, - cache_read_tokens: usage.cache_read_input_tokens, - reasoning_output_tokens: reasoning, + cache_creation_tokens: usage.cache_write_tokens, + cache_read_tokens: usage.cache_read_tokens, + reasoning_output_tokens, dedup_key, - }) + nano_aiu: metrics.total_nano_aiu, + premium_request_cost: metrics.requests.cost, + } } -struct CandidateSets { - chat_traces: HashSet, - inference_traces: HashSet, - agent_turn_traces: HashSet, - chat_response_ids: HashSet, - inference_response_ids: HashSet, - agent_turn_response_ids: HashSet, +fn build_aggregate_credit_entry( + session_id: &str, + nano_aiu: u64, + timestamp: TimestampMs, +) -> CopilotUsageEntry { + CopilotUsageEntry { + timestamp, + timestamp_text: crate::format_rfc3339_millis(timestamp), + session_id: session_id.to_string(), + model: String::new(), + input_tokens: 0, + output_tokens: 0, + cache_creation_tokens: 0, + cache_read_tokens: 0, + reasoning_output_tokens: 0, + dedup_key: format!("credit-aggregate:{session_id}:{nano_aiu}"), + nano_aiu: Some(nano_aiu), + premium_request_cost: None, + } } -impl CandidateSets { - fn new(candidates: &[CopilotUsageCandidate]) -> Self { - Self { - chat_traces: source_trace_ids(candidates, CopilotUsageSource::ChatSpan), - inference_traces: source_trace_ids(candidates, CopilotUsageSource::InferenceLog), - agent_turn_traces: source_trace_ids(candidates, CopilotUsageSource::AgentTurnLog), - chat_response_ids: source_response_ids(candidates, CopilotUsageSource::ChatSpan), - inference_response_ids: source_response_ids( - candidates, - CopilotUsageSource::InferenceLog, - ), - agent_turn_response_ids: source_response_ids( - candidates, - CopilotUsageSource::AgentTurnLog, - ), +fn session_id_from_path(path: &Path) -> Option { + path.parent() + .and_then(Path::file_name) + .and_then(|name| name.to_str()) + .map(str::to_string) +} + +/// Strips Copilot routing suffixes and normalizes Claude dots for LiteLLM pricing lookup. +pub(super) fn normalize_copilot_model(raw: &str) -> std::borrow::Cow<'_, str> { + const SUFFIXES: &[&str] = &["-1m-internal", "-internal", "-xhigh", "-high", "-1m"]; + let mut trimmed: &str = raw; + for suffix in SUFFIXES { + if trimmed.ends_with(suffix) { + trimmed = &trimmed[..trimmed.len() - suffix.len()]; + break; } } -} -fn source_trace_ids( - candidates: &[CopilotUsageCandidate], - source: CopilotUsageSource, -) -> HashSet { - candidates - .iter() - .filter(|candidate| candidate.source == source) - .filter_map(|candidate| candidate.trace_id.clone()) - .collect() -} + if trimmed.starts_with("claude-") { + let dotted = claude_dot_to_dash(trimmed); + return std::borrow::Cow::Owned(dotted); + } -fn source_response_ids( - candidates: &[CopilotUsageCandidate], - source: CopilotUsageSource, -) -> HashSet { - candidates - .iter() - .filter(|candidate| candidate.source == source) - .filter_map(|candidate| candidate.response_id.clone()) - .collect() + if trimmed.as_ptr() == raw.as_ptr() && trimmed.len() == raw.len() { + std::borrow::Cow::Borrowed(raw) + } else { + std::borrow::Cow::Owned(trimmed.to_string()) + } } -fn should_emit_candidate(candidate: &CopilotUsageCandidate, sets: &CandidateSets) -> bool { - let trace_match = |values: &HashSet| { - candidate - .trace_id - .as_ref() - .is_some_and(|trace_id| values.contains(trace_id)) - }; - let response_match = |values: &HashSet| { - candidate - .response_id - .as_ref() - .is_some_and(|response_id| values.contains(response_id)) - }; - match candidate.source { - CopilotUsageSource::ChatSpan => true, - CopilotUsageSource::InferenceLog => { - !trace_match(&sets.chat_traces) && !response_match(&sets.chat_response_ids) - } - CopilotUsageSource::AgentTurnLog => { - !trace_match(&sets.chat_traces) - && !trace_match(&sets.inference_traces) - && !response_match(&sets.chat_response_ids) - && !response_match(&sets.inference_response_ids) - } - CopilotUsageSource::AgentSummarySpan => { - !trace_match(&sets.chat_traces) - && !trace_match(&sets.inference_traces) - && !trace_match(&sets.agent_turn_traces) - && !response_match(&sets.chat_response_ids) - && !response_match(&sets.inference_response_ids) - && !response_match(&sets.agent_turn_response_ids) +fn claude_dot_to_dash(value: &str) -> String { + // Rewrites `claude-opus-4.7` → `claude-opus-4-7` etc. (Convert ASCII + // dots between two ASCII digits to dashes.) Decode the input as `char` + // values rather than raw bytes so multi-byte UTF-8 model identifiers + // stay intact: today the `claude-` gate at the only call site keeps + // inputs ASCII, but if the upstream model identifier scheme ever + // included non-ASCII characters this helper must not corrupt them by + // re-encoding bytes as `char`. + // + // Streaming impl: walk the iterator with a single-char lookahead + // (`Peekable`) and a one-char trailing memory (`prev_ch`). Avoids + // collecting the full `Vec` that the previous implementation + // built, dropping a transient O(n) heap allocation on every Claude + // pricing lookup. + let mut out = String::with_capacity(value.len()); + let mut chars = value.chars().peekable(); + let mut prev_ch: Option = None; + while let Some(ch) = chars.next() { + let is_dot_between_digits = ch == '.' + && prev_ch.is_some_and(|p| p.is_ascii_digit()) + && chars.peek().is_some_and(|n| n.is_ascii_digit()); + if is_dot_between_digits { + out.push('-'); + } else { + out.push(ch); } + prev_ch = Some(ch); } + out } -const MODEL_ATTRS: &[&str] = &["gen_ai.response.model", "gen_ai.request.model"]; -const SESSION_ATTRS: &[(&str, u8)] = &[ - ("gen_ai.conversation.id", 3), - ("copilot_chat.session_id", 3), - ("copilot_chat.chat_session_id", 3), - ("session.id", 3), - ("github.copilot.interaction_id", 2), - ("gen_ai.response.id", 1), -]; - -fn is_span_record(record: &CopilotRecord) -> bool { - if let Some(record_type) = record.record_type.as_ref().and_then(Value::as_str) { - return record_type == "span"; - } - string_value(record.name.as_ref()).is_some() - && (string_value(record.span_id.as_ref()).is_some() - || string_value(record.trace_id.as_ref()).is_some() - || record.start_time.is_some() - || record.end_time.is_some() - || record.duration.is_some() - || record.kind.is_some()) -} +#[cfg(test)] +mod session_state_tests { + use serde_json::json; -fn is_chat_span_record(record: &CopilotRecord, attributes: &Map) -> bool { - is_span_record(record) - && (attr_string(attributes, "gen_ai.operation.name").as_deref() == Some("chat") - || string_value(record.name.as_ref()).is_some_and(|name| name.starts_with("chat "))) -} + use super::*; -fn is_agent_summary_span_record(record: &CopilotRecord, attributes: &Map) -> bool { - is_span_record(record) - && (attr_string(attributes, "gen_ai.operation.name").as_deref() == Some("invoke_agent") - || string_value(record.name.as_ref()) - .is_some_and(|name| name.starts_with("invoke_agent "))) -} + fn write_jsonl(lines: &[String]) -> (ccusage_test_support::Fixture, std::path::PathBuf) { + // Mirror real layout: //events.jsonl + let fixture = ccusage_test_support::Fixture::new(); + let mut content = lines.join("\n"); + if !content.ends_with('\n') { + content.push('\n'); + } + let path = fixture.write_file("abc123-test-session/events.jsonl", content.as_str()); + (fixture, path) + } -fn is_inference_log_record(record: &CopilotRecord, attributes: &Map) -> bool { - !is_span_record(record) - && (attr_string(attributes, "event.name").as_deref() - == Some("gen_ai.client.inference.operation.details") - || record_body(record).is_some_and(|body| body.starts_with("GenAI inference:"))) -} + fn shutdown_event(id: &str, ts: &str, model_metrics: serde_json::Value) -> String { + json!({ + "type": "session.shutdown", + "id": id, + "timestamp": ts, + "data": {"modelMetrics": model_metrics}, + }) + .to_string() + } -fn is_agent_turn_log_record(record: &CopilotRecord, attributes: &Map) -> bool { - !is_span_record(record) - && (attr_string(attributes, "event.name").as_deref() == Some("copilot_chat.agent.turn") - || record_body(record).is_some_and(|body| body.starts_with("copilot_chat.agent.turn"))) -} + #[test] + fn accepts_fractional_premium_request_cost() { + // Real-data invariant: ~2% of shutdown rows ship fractional + // `requests.cost` values (e.g. Opus 4.7's `1 × 7.5 multiplier = + // 7.5`). If `cost` were typed as `u64`, the whole shutdown event + // would fail to deserialize and ALL of its models would be + // silently dropped — including the unrelated integer-cost + // siblings that happened to be in the same event. This fixture + // intentionally mixes a fractional row (Opus 4.7, cost 7.5) with + // an integer-cost sibling (Sonnet 4.5, cost 1 — 1 request × 1× + // multiplier) so the regression pins both the fractional row + // surviving AND the sibling not being collateral damage. + let (_dir, path) = write_jsonl(&[shutdown_event( + "evt-frac", + "2026-05-02T15:27:09.013Z", + json!({ + "claude-opus-4.7": { + "usage": { + "inputTokens": 1_000u64, + "outputTokens": 100u64, + "cacheReadTokens": 0u64, + "cacheWriteTokens": 0u64, + "reasoningTokens": 0u64 + }, + "requests": {"count": 1, "cost": 7.5} + }, + "claude-sonnet-4.5": { + "usage": { + "inputTokens": 2_000u64, + "outputTokens": 200u64, + "cacheReadTokens": 0u64, + "cacheWriteTokens": 0u64, + "reasoningTokens": 0u64 + }, + // Sonnet 4.5 has a 1× multiplier under the pre-cutover + // premium plan, so 1 request × 1× = cost 1 (integer). + "requests": {"count": 1, "cost": 1} + } + }), + )]); -fn dedup_key_for_record( - source: CopilotUsageSource, - record: &CopilotRecord, - attributes: &Map, - trace_id: &Option, - session_id: &str, - timestamp: TimestampMs, - index: usize, -) -> String { - let span_id = span_id_from_record(record); - match source { - CopilotUsageSource::ChatSpan | CopilotUsageSource::AgentSummarySpan => { - if let (Some(trace_id), Some(span_id)) = (trace_id, span_id) { - return format!("{trace_id}:{span_id}"); + let entries = parse_session_state_file(&path).unwrap(); + // Both rows must survive — the fractional cost on one row used to + // fail u64 deserialization and silently drop the entire event, + // including the unrelated integer-cost row it carried. + assert_eq!(entries.len(), 2, "got {entries:?}"); + let opus = entries + .iter() + .find(|e| e.model == "claude-opus-4.7") + .expect("opus row"); + assert_eq!(opus.premium_request_cost, Some(7.5)); + let sonnet = entries + .iter() + .find(|e| e.model == "claude-sonnet-4.5") + .expect("sonnet row (integer-cost sibling)"); + assert_eq!(sonnet.premium_request_cost, Some(1.0)); + } + + #[test] + fn absent_requests_cost_preserves_none_for_token_priced_fallback() { + // Forward-compat: today every observed Copilot session-state + // shutdown row ships `requests.cost`. If a future CLI ever drops + // that field, we MUST distinguish "absent" from "explicit 0" so + // Auto's dispatch can fall through to token-priced pricing rather + // than reporting a false `$0` bill from `Some(0.0) × $0.04`. + // This test pins the `cost: Option` shape: a row with no + // `cost` field deserializes to `premium_request_cost: None`. + let (_dir, path) = write_jsonl(&[shutdown_event( + "evt-no-cost", + "2026-05-02T15:27:09.013Z", + json!({ + "claude-opus-4.7-1m-internal": { + "usage": { + "inputTokens": 1_000u64, + "outputTokens": 100u64, + "cacheReadTokens": 0u64, + "cacheWriteTokens": 0u64, + "reasoningTokens": 0u64 + }, + // `cost` intentionally absent — `count` only. + "requests": {"count": 1} + } + }), + )]); + + let entries = parse_session_state_file(&path).unwrap(); + assert_eq!(entries.len(), 1); + assert_eq!( + entries[0].premium_request_cost, None, + "absent `cost` field must round-trip as None, not Some(0.0)" + ); + } + + #[test] + fn tolerates_float_valued_per_model_total_nano_aiu() { + // Forward-compat hardening (sibling to the fractional-cost fix): + // a future Copilot CLI that ships `totalNanoAiu` as a JSON float + // (e.g. `1500000000.0` after passing through a JS pipeline that + // coerces large integers to f64) must NOT fail the whole event + // deserialize and silently drop every model. The custom + // deserializer accepts both u64 and f64 forms and truncates floats + // to `u64`. Mix a float-valued per-model AIU with an integer-cost + // sibling so the test pins both the float row surviving AND the + // sibling not being collateral damage from a u64-only failure. + let (_dir, path) = write_jsonl(&[shutdown_event( + "evt-naiu-float", + "2026-05-20T16:01:29.481Z", + json!({ + "claude-opus-4.7-1m-internal": { + "usage": { + "inputTokens": 90_890_709u64, + "outputTokens": 172_544u64, + "cacheReadTokens": 86_415_643u64, + "cacheWriteTokens": 4_474_731u64, + "reasoningTokens": 0u64 + }, + "requests": {"count": 182, "cost": 4}, + "totalNanoAiu": 1_500_000_000.0_f64 + }, + "claude-sonnet-4.5": { + "usage": { + "inputTokens": 2_000u64, + "outputTokens": 200u64, + "cacheReadTokens": 0u64, + "cacheWriteTokens": 0u64, + "reasoningTokens": 0u64 + }, + "requests": {"count": 1, "cost": 1} + } + }), + )]); + + let entries = parse_session_state_file(&path).unwrap(); + // Both rows must survive — without the tolerant deserializer the + // float-valued AIU would fail u64 parsing and drop both models. + assert_eq!(entries.len(), 2, "got {entries:?}"); + let opus = entries + .iter() + .find(|e| e.model == "claude-opus-4.7-1m-internal") + .expect("opus row"); + assert_eq!(opus.nano_aiu, Some(1_500_000_000)); + let sonnet = entries + .iter() + .find(|e| e.model == "claude-sonnet-4.5") + .expect("sonnet row (integer-cost sibling)"); + assert_eq!(sonnet.premium_request_cost, Some(1.0)); + } + + #[test] + fn tolerates_float_valued_aggregate_total_nano_aiu() { + // Forward-compat hardening for the aggregate (session-level) + // `data.totalNanoAiu`: a float-valued aggregate must round-trip + // and reach the synthetic aggregate-credit entry. + let event = format!( + "{}\n", + json!({ + "type": "session.shutdown", + "id": "evt-agg-float", + "timestamp": "2026-05-20T16:01:29.481Z", + "data": { + "totalNanoAiu": 1_000_000_000.0_f64, + "modelMetrics": {} + } + }) + ); + let (_dir, path) = write_jsonl(&[event]); + let entries = parse_session_state_file(&path).unwrap(); + assert_eq!(entries.len(), 1); + assert!(entries[0].dedup_key.starts_with("credit-aggregate:")); + assert_eq!(entries[0].nano_aiu, Some(1_000_000_000)); + } + + #[test] + fn rejects_negative_float_total_nano_aiu() { + // `totalNanoAiu` is non-negative by definition (nano-units of a + // credit count). A negative value would be a schema bug; reject + // rather than coerce. The whole event is dropped via the + // tolerate-malformed-line path — preferable to silently round to + // zero and over-suppress the aggregate-credit guard. + let event = format!( + "{}\n", + json!({ + "type": "session.shutdown", + "id": "evt-naiu-neg", + "timestamp": "2026-05-20T16:01:29.481Z", + "data": { + "totalNanoAiu": -1.0_f64, + "modelMetrics": {} + } + }) + ); + let (_dir, path) = write_jsonl(&[event]); + let entries = parse_session_state_file(&path).unwrap(); + assert!( + entries.is_empty(), + "negative nano-AIU must reject the event (not coerce to zero), got {entries:?}" + ); + } + + #[test] + fn rejects_negative_premium_request_cost() { + // Parity with `rejects_negative_float_total_nano_aiu`. A + // premium-request count cannot legitimately be negative + // (`cost = count × multiplier`, both non-negative). A negative + // value would be a schema bug; reject rather than coerce. + // Critical concern: silently propagating `-1.5 × $0.04 = -$0.06` + // into the billing total would make the summary cost appear + // smaller than it really is — strictly worse than dropping the + // single malformed row. The whole event is dropped via the + // tolerate-malformed-line path because serde fails the WHOLE + // event on the custom-deserializer error. + // + // Verified to FAIL against the pre-fix default `f64` deserializer + // (which would have accepted `-1.5` and propagated it through + // billing). + // + // NOTE on NaN / ±Infinity: these are not representable in + // standard JSON (`serde_json` rejects the literal `NaN` / + // `Infinity` tokens at parse time before our deserializer + // runs), so a same-shape NaN regression test would be + // tautological — the line-skip path handles it via JSON + // parse failure, not via our custom-deserializer guard. The + // guard's `is_finite()` check is still useful as + // defense-in-depth against any future caller that constructs + // the struct from a non-JSON source. + let (_dir, path) = write_jsonl(&[shutdown_event( + "evt-cost-neg", + "2026-05-20T16:01:29.481Z", + json!({ + "claude-opus-4.7": { + "usage": { + "inputTokens": 100u64, + "outputTokens": 10u64, + "cacheReadTokens": 0u64, + "cacheWriteTokens": 0u64, + "reasoningTokens": 0u64 + }, + "requests": {"count": 1, "cost": -1.5_f64} + } + }), + )]); + let entries = parse_session_state_file(&path).unwrap(); + assert!( + entries.is_empty(), + "negative requests.cost must reject the event (not coerce to a \ + negative bill), got {entries:?}" + ); + } + + #[test] + fn parses_session_shutdown_event() { + let (_dir, path) = write_jsonl(&[shutdown_event( + "evt-1", + "2026-05-02T15:27:09.013Z", + json!({ + "claude-opus-4.7-1m-internal": { + "usage": { + "inputTokens": 90_890_709u64, + "outputTokens": 172_544u64, + "cacheReadTokens": 86_415_643u64, + "cacheWriteTokens": 4_474_731u64, + "reasoningTokens": 0u64 + }, + "requests": {"count": 182, "cost": 4} + }, + "gpt-5.4": { + "usage": { + "inputTokens": 30_000u64, + "outputTokens": 500u64, + "cacheReadTokens": 10_000u64, + "cacheWriteTokens": 5_000u64, + "reasoningTokens": 0u64 + }, + "requests": {"count": 2, "cost": 0} + } + }), + )]); + + let entries = parse_session_state_file(&path).unwrap(); + assert_eq!(entries.len(), 2); + + let opus = entries + .iter() + .find(|e| e.model == "claude-opus-4.7-1m-internal") + .expect("missing opus row"); + assert_eq!(opus.session_id, "abc123-test-session"); + assert_eq!( + opus.dedup_key, + "shutdown:abc123-test-session:evt-1:claude-opus-4.7-1m-internal" + ); + assert_eq!(opus.timestamp_text, "2026-05-02T15:27:09.013Z"); + // input - cache_read - cache_write = 90890709 - 86415643 - 4474731 = 335 + assert_eq!(opus.input_tokens, 335); + assert_eq!(opus.output_tokens, 172_544); + assert_eq!(opus.cache_read_tokens, 86_415_643); + assert_eq!(opus.cache_creation_tokens, 4_474_731); + assert_eq!(opus.reasoning_output_tokens, 0); + + let gpt = entries.iter().find(|e| e.model == "gpt-5.4").unwrap(); + assert_eq!(gpt.input_tokens, 30_000 - 10_000 - 5_000); + } + + #[test] + fn treats_resumed_session_shutdowns_as_distinct_entries() { + // Real-data pattern: same file, same model, two shutdowns with + // non-monotonic token counts (per-process snapshots, not cumulative). + let (_dir, path) = write_jsonl(&[ + shutdown_event( + "evt-first", + "2026-03-15T12:00:00.000Z", + json!({ + "claude-opus-4.6-1m": { + "usage": { + "inputTokens": 20_000u64, + "outputTokens": 1_000u64, + "cacheReadTokens": 15_000u64, + "cacheWriteTokens": 0u64, + "reasoningTokens": 0u64 + }, + "requests": {"count": 5, "cost": 3} + } + }), + ), + shutdown_event( + "evt-second", + "2026-03-16T09:00:00.000Z", + json!({ + "claude-opus-4.6-1m": { + "usage": { + "inputTokens": 8_000u64, + "outputTokens": 400u64, + "cacheReadTokens": 5_000u64, + "cacheWriteTokens": 0u64, + "reasoningTokens": 0u64 + }, + "requests": {"count": 2, "cost": 0} + } + }), + ), + ]); + + let entries = parse_session_state_file(&path).unwrap(); + assert_eq!(entries.len(), 2); + let mut keys: Vec<_> = entries.iter().map(|e| e.dedup_key.as_str()).collect(); + keys.sort(); + assert_eq!( + keys, + vec![ + "shutdown:abc123-test-session:evt-first:claude-opus-4.6-1m", + "shutdown:abc123-test-session:evt-second:claude-opus-4.6-1m", + ] + ); + // Confirm the smaller second value is preserved (not cumulative). + let second = entries + .iter() + .find(|e| e.dedup_key.contains("second")) + .unwrap(); + assert_eq!(second.output_tokens, 400); + } + + #[test] + fn skips_shutdown_with_empty_model_metrics() { + let (_dir, path) = write_jsonl(&[shutdown_event( + "evt-empty", + "2026-03-11T15:45:43.134Z", + json!({}), + )]); + assert!(parse_session_state_file(&path).unwrap().is_empty()); + } + + #[test] + fn skips_zero_token_and_zero_request_metrics() { + let (_dir, path) = write_jsonl(&[shutdown_event( + "evt-zero", + "2026-03-11T15:45:43.134Z", + json!({ + "claude-sonnet-4.5": { + "usage": { + "inputTokens": 0u64, + "outputTokens": 0u64, + "cacheReadTokens": 0u64, + "cacheWriteTokens": 0u64, + "reasoningTokens": 0u64 + }, + "requests": {"count": 0, "cost": 0} + } + }), + )]); + assert!(parse_session_state_file(&path).unwrap().is_empty()); + } + + #[test] + fn keeps_row_when_requests_present_even_with_zero_tokens() { + // PR #957's skip rule keeps rows when requests > 0 even with zero + // tokens. This is rare in real data but explicit in the spec. + let (_dir, path) = write_jsonl(&[shutdown_event( + "evt-req", + "2026-03-11T15:45:43.134Z", + json!({ + "claude-sonnet-4.5": { + "usage": { + "inputTokens": 0u64, + "outputTokens": 0u64, + "cacheReadTokens": 0u64, + "cacheWriteTokens": 0u64, + "reasoningTokens": 0u64 + }, + "requests": {"count": 1, "cost": 0} + } + }), + )]); + let entries = parse_session_state_file(&path).unwrap(); + assert_eq!(entries.len(), 1); + } + + #[test] + fn keeps_gemini_row_with_only_reasoning_tokens() { + // Symmetry guard for Gemini: `build_session_state_entry` preserves + // `reasoningTokens` verbatim for Gemini (separate field from + // output), so the skip rule must keep a Gemini row whose only + // non-zero usage is reasoning. Without the provider-gated + // reasoning clause in `no_tokens`, this row would be silently + // dropped here even though the entry construction would have + // surfaced 1234 reasoning output tokens. + let (_dir, path) = write_jsonl(&[shutdown_event( + "evt-reason-only", + "2026-03-11T15:45:43.134Z", + json!({ + "gemini-2.0-flash": { + "usage": { + "inputTokens": 0u64, + "outputTokens": 0u64, + "cacheReadTokens": 0u64, + "cacheWriteTokens": 0u64, + "reasoningTokens": 1_234u64 + }, + "requests": {"count": 0, "cost": 0} + } + }), + )]); + let entries = parse_session_state_file(&path).unwrap(); + assert_eq!(entries.len(), 1, "got {entries:?}"); + assert_eq!(entries[0].reasoning_output_tokens, 1_234); + } + + #[test] + fn skips_non_gemini_row_with_only_reasoning_tokens() { + // Symmetry guard for OpenAI/Anthropic: their reasoning tokens + // are subsumed into `output_tokens`, so a row with + // `output_tokens == 0 && reasoning_tokens > 0` is a contradiction + // the schema cannot legitimately emit. If it ever does appear + // (data corruption or a future schema change), the builder would + // hard-set `reasoning_output_tokens = 0` for the non-Gemini + // provider, producing an all-zero phantom entry. The + // provider-gated skip rule drops it instead, preserving the + // invariant that every surviving row carries at least one + // non-zero surfaced field. + let (_dir, path) = write_jsonl(&[shutdown_event( + "evt-non-gemini-reason", + "2026-03-11T15:45:43.134Z", + json!({ + "claude-opus-4.7": { + "usage": { + "inputTokens": 0u64, + "outputTokens": 0u64, + "cacheReadTokens": 0u64, + "cacheWriteTokens": 0u64, + "reasoningTokens": 1_234u64 + }, + "requests": {"count": 0, "cost": 0} + } + }), + )]); + let entries = parse_session_state_file(&path).unwrap(); + assert!( + entries.is_empty(), + "non-Gemini reasoning-only row must be dropped (the builder \ + would zero out reasoning_output_tokens, leaving an all-zero \ + phantom entry); got {entries:?}" + ); + } + + #[test] + fn ignores_string_session_shutdown_substring_inside_tool_arguments() { + // Real-world hazard: our own session currently writes a + // `tool.execution_start` event whose `arguments.command` contains the + // literal `"session.shutdown"`. A substring-only filter would emit a + // phantom row. + let tool_record = json!({ + "type": "tool.execution_start", + "id": "tool-1", + "timestamp": "2026-05-02T15:27:09.013Z", + "data": { + "toolName": "bash", + "arguments": {"command": "grep -l 'session.shutdown' events.jsonl"} } - format!("span:{session_id}:{}:{index}", timestamp.as_millis()) - } - CopilotUsageSource::InferenceLog => { - if let (Some(trace_id), Some(span_id)) = (trace_id, span_id) { - return format!("log:{trace_id}:{span_id}"); + }) + .to_string(); + let (_dir, path) = write_jsonl(&[tool_record]); + assert!(parse_session_state_file(&path).unwrap().is_empty()); + } + + #[test] + fn tolerates_malformed_jsonl_lines_and_invalid_utf8() { + let valid = shutdown_event( + "evt-good", + "2026-05-02T15:27:09.013Z", + json!({ + "claude-opus-4.6": { + "usage": { + "inputTokens": 100u64, + "outputTokens": 50u64, + "cacheReadTokens": 30u64, + "cacheWriteTokens": 10u64, + "reasoningTokens": 0u64 + }, + "requests": {"count": 1, "cost": 1} + } + }), + ); + + // Build file manually so we can splice in raw invalid UTF-8 bytes. + let fixture = ccusage_test_support::Fixture::new(); + let session_dir = fixture.create_dir_all("bad-utf8-session"); + let path = session_dir.join("events.jsonl"); + let mut bytes: Vec = Vec::new(); + bytes.extend_from_slice(b"not valid json\n"); + // Truncated multi-byte UTF-8 sequence — mirrors the real-world + // 3c9f15b5-... file at byte 69879195 (`0xe2` start of 3-byte char + // followed by EOF/newline). + bytes.extend_from_slice(b"\xe2\n"); + bytes.extend_from_slice(valid.as_bytes()); + bytes.push(b'\n'); + fs::write(&path, &bytes).unwrap(); + + let entries = parse_session_state_file(&path).unwrap(); + assert_eq!(entries.len(), 1, "expected the valid event to survive"); + assert_eq!(entries[0].model, "claude-opus-4.6"); + assert_eq!(entries[0].input_tokens, 100 - 30 - 10); + } + + #[test] + fn accepts_legacy_schema_without_reasoning_tokens() { + // 1.0.40-era data: no `reasoningTokens` field at all. + let (_dir, path) = write_jsonl(&[json!({ + "type": "session.shutdown", + "id": "evt-legacy", + "timestamp": "2026-02-28T09:52:27.352Z", + "data": {"modelMetrics": { + "claude-opus-4.6": { + "usage": { + "inputTokens": 1000u64, + "outputTokens": 100u64, + "cacheReadTokens": 500u64, + "cacheWriteTokens": 0u64 + }, + "requests": {"count": 1, "cost": 1} + } + }} + }) + .to_string()]); + let entries = parse_session_state_file(&path).unwrap(); + assert_eq!(entries.len(), 1); + assert_eq!(entries[0].reasoning_output_tokens, 0); + assert_eq!(entries[0].input_tokens, 500); + } + + #[test] + fn subtracts_both_cache_read_and_cache_write_from_input() { + // Regression pin for the documented invariant that session-state + // `inputTokens` is inclusive of both cache-read AND cache-write + // counts (see `build_session_state_entry`'s `input_only` derivation). + let (_dir, path) = write_jsonl(&[shutdown_event( + "evt-cache", + "2026-05-02T15:27:09.013Z", + json!({ + "claude-opus-4.7": { + "usage": { + "inputTokens": 100u64, + "outputTokens": 5u64, + "cacheReadTokens": 60u64, + "cacheWriteTokens": 30u64, + "reasoningTokens": 0u64 + }, + "requests": {"count": 1, "cost": 1} + } + }), + )]); + let entries = parse_session_state_file(&path).unwrap(); + assert_eq!( + entries[0].input_tokens, 10, + "100 - 60 - 30 = 10 fresh input" + ); + assert_eq!(entries[0].cache_read_tokens, 60); + assert_eq!(entries[0].cache_creation_tokens, 30); + assert_eq!(entries[0].output_tokens, 5); + } + + #[test] + fn ignores_token_details_field_even_when_present() { + // Real-data divergence case: `usage.*` and `tokenDetails.*` are + // independent snapshots in ~31% of rows. We must use `usage.*` only. + let event = json!({ + "type": "session.shutdown", + "id": "evt-td", + "timestamp": "2026-05-02T15:27:09.013Z", + "data": { + "tokenDetails": { + "input": {"tokenCount": 999_999u64}, + "output": {"tokenCount": 888_888u64}, + "cache_read": {"tokenCount": 777_777u64}, + "cache_write": {"tokenCount": 666_666u64} + }, + "modelMetrics": { + "claude-opus-4.7-1m-internal": { + "usage": { + "inputTokens": 100u64, + "outputTokens": 5u64, + "cacheReadTokens": 60u64, + "cacheWriteTokens": 30u64, + "reasoningTokens": 0u64 + }, + "requests": {"count": 1, "cost": 1}, + "tokenDetails": { + "input": {"tokenCount": 50u64}, + "output": {"tokenCount": 25u64}, + "cache_read": {"tokenCount": 555u64}, + "cache_write": {"tokenCount": 333u64} + } + } + } } - format!("log:{session_id}:{}:{index}", timestamp.as_millis()) - } - CopilotUsageSource::AgentTurnLog => { - let turn_index = number_value(attributes.get("turn.index")) - .or_else(|| number_value(attributes.get("copilot_chat.turn.index"))) - .map_or_else(|| format!("idx-{index}"), |value| value.to_string()); - trace_id.as_ref().map_or_else( - || format!("agent-turn:{session_id}:{turn_index}:{index}"), - |trace_id| format!("agent-turn:{trace_id}:{turn_index}"), - ) - } + }) + .to_string(); + let (_dir, path) = write_jsonl(&[event]); + let entries = parse_session_state_file(&path).unwrap(); + assert_eq!(entries.len(), 1); + // Values come from usage.*, NOT tokenDetails.* + assert_eq!(entries[0].input_tokens, 10); + assert_eq!(entries[0].output_tokens, 5); + assert_eq!(entries[0].cache_read_tokens, 60); + assert_eq!(entries[0].cache_creation_tokens, 30); } -} -fn trace_id_from_record(record: &CopilotRecord) -> Option { - string_value(record.trace_id.as_ref()) - .map(str::to_string) - .or_else(|| nested_string(record.span_context.as_ref(), "traceId")) -} + #[test] + fn preserves_raw_model_name_on_entry() { + // Source-fidelity check: the raw `claude-opus-4.7-1m-internal` name + // must reach `entry.model` unchanged. Normalization happens at + // pricing-lookup time in the loader, not here. + let (_dir, path) = write_jsonl(&[shutdown_event( + "evt-raw", + "2026-05-02T15:27:09.013Z", + json!({ + "claude-opus-4.7-1m-internal": { + "usage": { + "inputTokens": 100u64, + "outputTokens": 10u64, + "cacheReadTokens": 0u64, + "cacheWriteTokens": 0u64, + "reasoningTokens": 0u64 + }, + "requests": {"count": 1, "cost": 1} + } + }), + )]); + let entries = parse_session_state_file(&path).unwrap(); + assert_eq!(entries[0].model, "claude-opus-4.7-1m-internal"); + } -fn span_id_from_record(record: &CopilotRecord) -> Option { - string_value(record.span_id.as_ref()) - .map(str::to_string) - .or_else(|| nested_string(record.span_context.as_ref(), "spanId")) -} + #[test] + fn gpt_reasoning_set_to_zero_to_avoid_double_count() { + // OpenAI convention: reasoning IS a subset of output. Adding the + // raw `reasoning_tokens` into the summary again via + // `TokenCounts::total` (`types.rs`) would over-count cost ~40%. + let (_dir, path) = write_jsonl(&[shutdown_event( + "evt-gpt", + "2026-05-02T15:27:09.013Z", + json!({ + "gpt-5.4": { + "usage": { + "inputTokens": 1000u64, + "outputTokens": 6612u64, + "cacheReadTokens": 0u64, + "cacheWriteTokens": 0u64, + "reasoningTokens": 536u64 + }, + "requests": {"count": 1, "cost": 0} + } + }), + )]); + let entries = parse_session_state_file(&path).unwrap(); + assert_eq!(entries[0].output_tokens, 6612); + assert_eq!(entries[0].reasoning_output_tokens, 0); + } -fn nested_string(object: Option<&Value>, key: &str) -> Option { - object - .and_then(Value::as_object) - .and_then(|object| string_value(object.get(key))) - .map(str::to_string) -} + #[test] + fn claude_reasoning_set_to_zero_to_avoid_double_count() { + // Empirically verified: 48/48 local Claude rows with `reason > 0` + // have `reason ≤ out` (subset). Anthropic billing folds extended + // thinking into output_tokens. + let (_dir, path) = write_jsonl(&[shutdown_event( + "evt-claude", + "2026-05-02T15:27:09.013Z", + json!({ + "claude-opus-4.7-xhigh": { + "usage": { + "inputTokens": 1000u64, + "outputTokens": 163_851u64, + "cacheReadTokens": 0u64, + "cacheWriteTokens": 0u64, + "reasoningTokens": 19_382u64 + }, + "requests": {"count": 1, "cost": 0} + } + }), + )]); + let entries = parse_session_state_file(&path).unwrap(); + assert_eq!(entries[0].output_tokens, 163_851); + assert_eq!(entries[0].reasoning_output_tokens, 0); + } -fn record_body(record: &CopilotRecord) -> Option<&str> { - string_value(record.body.as_ref()).or_else(|| string_value(record.underscore_body.as_ref())) -} + #[test] + fn gemini_reasoning_kept_because_separate_from_output() { + // Google convention: candidatesTokenCount and thoughtsTokenCount are + // SEPARATE fields. Real-data sample had reason(6340) > out(3037). + let (_dir, path) = write_jsonl(&[shutdown_event( + "evt-gem", + "2026-05-02T15:27:09.013Z", + json!({ + "gemini-3.1-pro-preview": { + "usage": { + "inputTokens": 1000u64, + "outputTokens": 3037u64, + "cacheReadTokens": 0u64, + "cacheWriteTokens": 0u64, + "reasoningTokens": 6340u64 + }, + "requests": {"count": 1, "cost": 0} + } + }), + )]); + let entries = parse_session_state_file(&path).unwrap(); + assert_eq!(entries[0].output_tokens, 3037); + assert_eq!(entries[0].reasoning_output_tokens, 6340); + } -fn string_value(value: Option<&Value>) -> Option<&str> { - let value = value?.as_str()?.trim(); - (!value.is_empty()).then_some(value) -} + #[test] + fn unknown_provider_defaults_to_subset_semantics() { + let (_dir, path) = write_jsonl(&[shutdown_event( + "evt-unk", + "2026-05-02T15:27:09.013Z", + json!({ + "vendor-x-pro": { + "usage": { + "inputTokens": 100u64, + "outputTokens": 100u64, + "cacheReadTokens": 0u64, + "cacheWriteTokens": 0u64, + "reasoningTokens": 50u64 + }, + "requests": {"count": 1, "cost": 0} + } + }), + )]); + let entries = parse_session_state_file(&path).unwrap(); + assert_eq!(entries[0].reasoning_output_tokens, 0); + } -fn number_value(value: Option<&Value>) -> Option { - match value? { - Value::Number(number) => number.as_u64().or_else(|| { - number - .as_i64() - .and_then(|value| (value >= 0).then_some(value as u64)) - }), - Value::String(text) => text.trim().parse::().ok(), - _ => None, + #[test] + fn normalize_copilot_model_strips_internal_suffixes() { + assert_eq!( + normalize_copilot_model("claude-opus-4.7-1m-internal").as_ref(), + "claude-opus-4-7" + ); + assert_eq!( + normalize_copilot_model("claude-opus-4.7-xhigh").as_ref(), + "claude-opus-4-7" + ); + assert_eq!( + normalize_copilot_model("claude-opus-4.6-1m").as_ref(), + "claude-opus-4-6" + ); + assert_eq!( + normalize_copilot_model("claude-opus-4.7-high").as_ref(), + "claude-opus-4-7" + ); + assert_eq!( + normalize_copilot_model("claude-opus-4.7-internal").as_ref(), + "claude-opus-4-7" + ); } -} -fn attr_string(attributes: &Map, key: &str) -> Option { - string_value(attributes.get(key)).map(str::to_string) -} + #[test] + fn normalize_copilot_model_converts_claude_dots_to_dashes() { + assert_eq!( + normalize_copilot_model("claude-opus-4.6").as_ref(), + "claude-opus-4-6" + ); + assert_eq!( + normalize_copilot_model("claude-sonnet-4.5").as_ref(), + "claude-sonnet-4-5" + ); + assert_eq!( + normalize_copilot_model("claude-haiku-4.5").as_ref(), + "claude-haiku-4-5" + ); + } -fn attr_number(attributes: &Map, key: &str) -> u64 { - number_value(attributes.get(key)).unwrap_or_default() -} + #[test] + fn normalize_copilot_model_preserves_gpt_dotted_names() { + assert_eq!(normalize_copilot_model("gpt-5.4").as_ref(), "gpt-5.4"); + assert_eq!( + normalize_copilot_model("gpt-5.4-mini").as_ref(), + "gpt-5.4-mini" + ); + assert_eq!(normalize_copilot_model("gpt-5.5").as_ref(), "gpt-5.5"); + } -fn attr_number_first(attributes: &Map, keys: &[&str]) -> u64 { - keys.iter() - .map(|key| attr_number(attributes, key)) - .find(|value| *value > 0) - .unwrap_or_default() -} + #[test] + fn normalize_copilot_model_passes_through_unknown_models() { + assert_eq!(normalize_copilot_model("goldeneye").as_ref(), "goldeneye"); + assert_eq!( + normalize_copilot_model("vendor-x-pro").as_ref(), + "vendor-x-pro" + ); + } -fn first_non_empty_attr(attributes: &Map, keys: &[&str]) -> Option { - keys.iter().find_map(|key| attr_string(attributes, key)) -} + #[test] + fn claude_dot_to_dash_preserves_multi_byte_utf8_characters() { + // Regression pin: the helper used to iterate `value.as_bytes()` + // and `out.push(byte as char)`, which corrupts any multi-byte + // UTF-8 sequence (each non-ASCII byte gets reinterpreted as a + // U+0000..U+00FF char). The `claude-` gate at the only call + // site keeps real inputs ASCII today, but the helper itself + // must be UTF-8-safe for forward-compat — model identifiers + // could plausibly grow to include non-ASCII suffixes someday. + // + // Pin three properties: + // 1. Mixed ASCII-digit dots still convert to dashes. + // 2. Multi-byte UTF-8 characters round-trip unchanged. + // 3. A `.` adjacent to a non-ASCII-digit char is NOT converted + // (the guard checks `is_ascii_digit()` on both sides). + assert_eq!( + super::claude_dot_to_dash("claude-opus-4.7"), + "claude-opus-4-7" + ); + assert_eq!( + super::claude_dot_to_dash("claude-opus-4.7-café"), + "claude-opus-4-7-café", + "multi-byte UTF-8 (é = 2 bytes) must round-trip" + ); + // A dot between a digit and a non-ASCII-digit char should NOT + // be converted — `日` is digit-shaped but not ASCII digit. + assert_eq!( + super::claude_dot_to_dash("claude-opus-4.日"), + "claude-opus-4.日" + ); + } -fn best_session_attr(attributes: &Map) -> Option<(String, u8)> { - SESSION_ATTRS - .iter() - .filter_map(|(key, priority)| attr_string(attributes, key).map(|value| (value, *priority))) - .max_by_key(|(_, priority)| *priority) -} + // ----- AI Credits tests (totalNanoAiu) ----- -fn timestamp_from_record(record: &CopilotRecord) -> Option { - timestamp_from_parts(record.end_time.as_ref()) - .or_else(|| timestamp_from_parts(record.start_time.as_ref())) - .or_else(|| timestamp_from_parts(record.hr_time.as_ref())) - .or_else(|| timestamp_from_parts(record.underscore_hr_time.as_ref())) - .or_else(|| timestamp_from_parts(record.time.as_ref())) - .or_else(|| timestamp_from_scalar(record.timestamp.as_ref())) - .or_else(|| timestamp_from_scalar(record.observed_timestamp.as_ref())) - .or_else(|| timestamp_from_unix_nanos(record.time_unix_nano.as_ref())) -} + fn shutdown_event_with_naiu( + id: &str, + ts: &str, + model_metrics: serde_json::Value, + aggregate_naiu: Option, + ) -> String { + let mut data = json!({"modelMetrics": model_metrics}); + if let Some(naiu) = aggregate_naiu { + data.as_object_mut() + .unwrap() + .insert("totalNanoAiu".to_string(), json!(naiu)); + } + json!({ + "type": "session.shutdown", + "id": id, + "timestamp": ts, + "data": data, + }) + .to_string() + } -fn timestamp_from_parts(value: Option<&Value>) -> Option { - let values = value?.as_array()?; - let seconds = number_value(values.first())?; - let nanos = number_value(values.get(1))?; - let millis = seconds.checked_mul(1_000)?.checked_add(nanos / 1_000_000)?; - Some(TimestampMs::from_millis(millis.min(i64::MAX as u64) as i64)) -} + #[test] + fn parses_per_model_total_nano_aiu() { + let (_dir, path) = write_jsonl(&[shutdown_event_with_naiu( + "evt-credits", + "2026-05-20T16:01:29.481Z", + json!({ + "claude-opus-4.7-1m-internal": { + "usage": { + "inputTokens": 90_890_709u64, + "outputTokens": 172_544u64, + "cacheReadTokens": 86_415_643u64, + "cacheWriteTokens": 4_474_731u64, + "reasoningTokens": 0u64 + }, + "requests": {"count": 182, "cost": 4}, + "totalNanoAiu": 7_549_016_525_000u64 + } + }), + None, + )]); + let entries = parse_session_state_file(&path).unwrap(); + assert_eq!(entries.len(), 1); + assert_eq!(entries[0].nano_aiu, Some(7_549_016_525_000)); + } -fn timestamp_from_scalar(value: Option<&Value>) -> Option { - let raw = number_value(value)?; - let millis = if raw >= 100_000_000_000_000_000 { - raw / 1_000_000 - } else if raw >= 100_000_000_000_000 { - raw / 1_000 - } else if raw >= 100_000_000_000 { - raw - } else { - raw * 1_000 - }; - Some(TimestampMs::from_millis(millis.min(i64::MAX as u64) as i64)) -} + #[test] + fn keeps_zero_token_row_when_per_model_total_nano_aiu_is_present() { + // Real-data shape from 1135875b-… and 76dc438a-… events.jsonl: + // zero tokens, zero requests, non-null per-model totalNanoAiu. + let (_dir, path) = write_jsonl(&[shutdown_event_with_naiu( + "evt-credit-only", + "2026-05-20T16:01:29.481Z", + json!({ + "claude-opus-4.7-1m-internal": { + "usage": { + "inputTokens": 0u64, + "outputTokens": 0u64, + "cacheReadTokens": 0u64, + "cacheWriteTokens": 0u64, + "reasoningTokens": 0u64 + }, + "requests": {"count": 0, "cost": 0}, + "totalNanoAiu": 154_481_000_000u64 + } + }), + None, + )]); + let entries = parse_session_state_file(&path).unwrap(); + assert_eq!(entries.len(), 1); + assert_eq!(entries[0].nano_aiu, Some(154_481_000_000)); + // Token fields are still zero — this is informational credit-only. + assert_eq!(entries[0].input_tokens, 0); + assert_eq!(entries[0].output_tokens, 0); + // Dedup key is content-based for credit-only rows. + assert!( + entries[0].dedup_key.starts_with("credit-shutdown:"), + "got dedup_key={}", + entries[0].dedup_key + ); + } -fn timestamp_from_unix_nanos(value: Option<&Value>) -> Option { - let raw = number_value(value)?; - (raw > 0).then(|| TimestampMs::from_millis((raw / 1_000_000).min(i64::MAX as u64) as i64)) -} + #[test] + fn dedupes_identical_credit_only_rows_within_same_session() { + // Models the real-data duplicate pair in 1135875b-…/events.jsonl: + // two distinct shutdown events, both zero-token, both with the same + // per-model totalNanoAiu. After the parser these get the same + // content-based dedup key and the downstream HashMap collapses them. + let (_dir, path) = write_jsonl(&[ + shutdown_event_with_naiu( + "evt-first", + "2026-05-20T16:01:29.481Z", + json!({ + "claude-opus-4.7-1m-internal": { + "usage": { + "inputTokens": 0u64, + "outputTokens": 0u64, + "cacheReadTokens": 0u64, + "cacheWriteTokens": 0u64, + "reasoningTokens": 0u64 + }, + "requests": {"count": 0, "cost": 0}, + "totalNanoAiu": 154_481_000_000u64 + } + }), + None, + ), + shutdown_event_with_naiu( + "evt-second", + "2026-05-20T18:08:30.785Z", + json!({ + "claude-opus-4.7-1m-internal": { + "usage": { + "inputTokens": 0u64, + "outputTokens": 0u64, + "cacheReadTokens": 0u64, + "cacheWriteTokens": 0u64, + "reasoningTokens": 0u64 + }, + "requests": {"count": 0, "cost": 0}, + "totalNanoAiu": 154_481_000_000u64 + } + }), + None, + ), + ]); + let entries = parse_session_state_file(&path).unwrap(); + // The parser emits both candidates (it doesn't dedup itself), but + // both share the same content-based key for the loader-side HashMap. + assert_eq!(entries.len(), 2); + assert_eq!(entries[0].dedup_key, entries[1].dedup_key); + assert!(entries[0].dedup_key.starts_with("credit-shutdown:")); + } -fn file_modified_timestamp(path: &Path) -> TimestampMs { - fs::metadata(path) - .and_then(|metadata| metadata.modified()) - .ok() - .and_then(|modified| modified.duration_since(std::time::UNIX_EPOCH).ok()) - .map(|duration| TimestampMs::from_millis(duration.as_millis().min(i64::MAX as u128) as i64)) - .unwrap_or_else(crate::utc_now) + #[test] + fn token_bearing_rows_keep_event_id_dedup_key_not_content_based() { + // Two distinct shutdowns producing the same number of tokens MUST + // stay distinct (per-process snapshots). Only zero-token + // credit-only rows use the content-based key. + let (_dir, path) = write_jsonl(&[ + shutdown_event_with_naiu( + "evt-A", + "2026-05-20T16:01:29.481Z", + json!({ + "claude-opus-4.7-1m-internal": { + "usage": { + "inputTokens": 100u64, + "outputTokens": 50u64, + "cacheReadTokens": 0u64, + "cacheWriteTokens": 0u64, + "reasoningTokens": 0u64 + }, + "requests": {"count": 1, "cost": 0}, + "totalNanoAiu": 1_000_000_000u64 + } + }), + None, + ), + shutdown_event_with_naiu( + "evt-B", + "2026-05-20T18:08:30.785Z", + json!({ + "claude-opus-4.7-1m-internal": { + "usage": { + "inputTokens": 100u64, + "outputTokens": 50u64, + "cacheReadTokens": 0u64, + "cacheWriteTokens": 0u64, + "reasoningTokens": 0u64 + }, + "requests": {"count": 1, "cost": 0}, + "totalNanoAiu": 1_000_000_000u64 + } + }), + None, + ), + ]); + let entries = parse_session_state_file(&path).unwrap(); + assert_eq!(entries.len(), 2); + let mut keys: Vec<_> = entries.iter().map(|e| e.dedup_key.clone()).collect(); + keys.sort(); + assert_eq!( + keys, + vec![ + "shutdown:abc123-test-session:evt-A:claude-opus-4.7-1m-internal".to_string(), + "shutdown:abc123-test-session:evt-B:claude-opus-4.7-1m-internal".to_string(), + ] + ); + } + + #[test] + fn gemini_reasoning_only_rows_keep_event_id_dedup_key_not_content_based() { + // Gemini rows preserve `reasoning_output_tokens` as real billable + // usage (the only provider where the parser keeps that field + // non-zero — see `build_session_state_entry`). The dedup-key + // selector's `zero_token` check MUST include + // `reasoning_output_tokens` so a Gemini row with ONLY reasoning + // tokens (no input/output/cache, count=0, naiu set) is treated + // as token-bearing — using the event-id dedup key, not the + // content-based `credit-shutdown:` key. + // + // Without this guard, two distinct shutdowns in the same session + // with the same Gemini model + same `totalNanoAiu` value would + // produce identical `credit-shutdown:{session}:{model}:{naiu}` + // keys and collapse in the loader's `HashMap` dedup — silently + // under-counting reasoning tokens AND credits. + // + // Construct two shutdowns matching exactly that shape and pin + // that BOTH survive with distinct event-id keys. + let (_dir, path) = write_jsonl(&[ + shutdown_event_with_naiu( + "evt-gem-A", + "2026-05-20T16:01:29.481Z", + json!({ + "gemini-2.0-flash": { + "usage": { + "inputTokens": 0u64, + "outputTokens": 0u64, + "cacheReadTokens": 0u64, + "cacheWriteTokens": 0u64, + "reasoningTokens": 500u64 + }, + "requests": {"count": 0, "cost": 0}, + "totalNanoAiu": 1_000_000_000u64 + } + }), + None, + ), + shutdown_event_with_naiu( + "evt-gem-B", + "2026-05-20T18:08:30.785Z", + json!({ + "gemini-2.0-flash": { + "usage": { + "inputTokens": 0u64, + "outputTokens": 0u64, + "cacheReadTokens": 0u64, + "cacheWriteTokens": 0u64, + "reasoningTokens": 500u64 + }, + "requests": {"count": 0, "cost": 0}, + "totalNanoAiu": 1_000_000_000u64 + } + }), + None, + ), + ]); + let entries = parse_session_state_file(&path).unwrap(); + // Two distinct shutdowns must produce two distinct entries. + // Before the fix, both would have collapsed to the same + // `credit-shutdown:{session}:gemini-2.0-flash:1000000000` key. + assert_eq!( + entries.len(), + 2, + "two distinct Gemini reasoning-only shutdowns must NOT collapse \ + via the credit-only dedup path; got {entries:?}" + ); + let mut keys: Vec<_> = entries.iter().map(|e| e.dedup_key.clone()).collect(); + keys.sort(); + assert_eq!( + keys, + vec![ + "shutdown:abc123-test-session:evt-gem-A:gemini-2.0-flash".to_string(), + "shutdown:abc123-test-session:evt-gem-B:gemini-2.0-flash".to_string(), + ], + "Gemini reasoning-only rows must use event-id dedup keys, not \ + the content-based credit-only key" + ); + // Sanity: reasoning tokens preserved on each entry (Gemini path). + assert!(entries.iter().all(|e| e.reasoning_output_tokens == 500)); + } + + #[test] + fn aggregate_only_total_nano_aiu_emits_synthetic_entry() { + // Synthetic / forward-compat path: shutdown has data.totalNanoAiu but + // none of the per-model rows carry it. Not observed in real local + // data — kept as a guard against future schema variants. + let (_dir, path) = write_jsonl(&[shutdown_event_with_naiu( + "evt-agg", + "2026-05-20T16:01:29.481Z", + // Empty modelMetrics: only the aggregate carries credits. + json!({}), + Some(12_345_000_000), + )]); + let entries = parse_session_state_file(&path).unwrap(); + assert_eq!(entries.len(), 1); + assert!(entries[0].model.is_empty()); + assert_eq!(entries[0].nano_aiu, Some(12_345_000_000)); + assert!(entries[0].dedup_key.starts_with("credit-aggregate:")); + } + + #[test] + fn aggregate_credit_dedup_key_omits_event_id_to_collapse_duplicate_snapshots() { + // Mirror the per-model credit-only path's content-based dedup + // (`credit-shutdown:{session_id}:{model}:{naiu}` — observed to + // collapse duplicate snapshot pairs in real session-state data): + // if a future Copilot CLI ever ships aggregate-only credit + // snapshots in the same duplicate-pair pattern as per-model rows, + // they must collapse on `(session_id, naiu)` rather than survive + // distinct on `event_id` and silently double-bill the same total. + // + // This pins the symmetry: two aggregate-only shutdowns with + // distinct event ids but identical `totalNanoAiu` produce + // identical dedup keys, so the loader's `HashMap` collapse keeps + // exactly one row. + let (_dir, path) = write_jsonl(&[ + shutdown_event_with_naiu( + "evt-agg-first", + "2026-05-20T16:01:29.481Z", + json!({}), + Some(7_500_000_000), + ), + shutdown_event_with_naiu( + "evt-agg-second", + "2026-05-20T16:01:29.482Z", + json!({}), + Some(7_500_000_000), + ), + ]); + let entries = parse_session_state_file(&path).unwrap(); + assert_eq!(entries.len(), 2); + // Both surface from the parser at this stage; the loader collapses + // them via the `HashMap` strategy. Pin the identical-key + // property here (the per-file step) — the loader test + // `loader_dedup_keeps_distinct_sessions_with_colliding_event_ids` + // exercises the actual HashMap collapse downstream. + assert_eq!(entries[0].dedup_key, entries[1].dedup_key); + assert!(entries[0].dedup_key.starts_with("credit-aggregate:")); + assert!( + !entries[0].dedup_key.contains("evt-agg"), + "aggregate-credit dedup key must NOT include event_id (silent \ + double-count if duplicate snapshots appear); got {}", + entries[0].dedup_key + ); + } + + #[test] + fn aggregate_total_nano_aiu_is_suppressed_when_per_model_already_carries_it() { + // When the aggregate IS present AND at least one per-model row also + // has its own naiu, we trust the per-model rows and skip the + // synthetic aggregate path (which would otherwise double-count). + let (_dir, path) = write_jsonl(&[shutdown_event_with_naiu( + "evt-both", + "2026-05-20T16:01:29.481Z", + json!({ + "claude-opus-4.7-1m-internal": { + "usage": { + "inputTokens": 100u64, + "outputTokens": 10u64, + "cacheReadTokens": 0u64, + "cacheWriteTokens": 0u64, + "reasoningTokens": 0u64 + }, + "requests": {"count": 1, "cost": 0}, + "totalNanoAiu": 5_000_000_000u64 + } + }), + Some(5_000_000_000), + )]); + let entries = parse_session_state_file(&path).unwrap(); + // Per-model entry only — no synthetic aggregate row. + assert_eq!(entries.len(), 1); + assert!(!entries[0].model.is_empty()); + } + + #[test] + fn aggregate_credit_is_suppressed_when_per_model_has_premium_cost_only() { + // Latent double-count guard: a future shape with `data.totalNanoAiu + // > 0` AND per-model rows that carry `requests.cost > 0` but NO + // per-model `totalNanoAiu` would otherwise bill the SAME usage + // twice — once via Auto's premium ladder (`cost × $0.04` on the + // per-model row) and again via Auto's AIU ladder (`naiu × $0.01` + // on the synthetic). The narrow guard (`cost > 0` OR `naiu > 0`) + // suppresses the synthetic exactly in this case. + let (_dir, path) = write_jsonl(&[shutdown_event_with_naiu( + "evt-premium-and-aggregate", + "2026-05-20T16:01:29.481Z", + json!({ + "claude-opus-4.7-1m-internal": { + "usage": { + "inputTokens": 100u64, + "outputTokens": 10u64, + "cacheReadTokens": 0u64, + "cacheWriteTokens": 0u64, + "reasoningTokens": 0u64 + }, + "requests": {"count": 1, "cost": 7.5} + // No per-model totalNanoAiu — only the aggregate has AIU. + } + }), + Some(1_000_000_000), + )]); + let entries = parse_session_state_file(&path).unwrap(); + // Only the per-model row — synthetic suppressed to avoid + // double-counting the same usage in AIU + premium currencies. + assert_eq!(entries.len(), 1); + assert!( + !entries + .iter() + .any(|e| e.dedup_key.starts_with("credit-aggregate:")) + ); + assert!(!entries[0].model.is_empty()); + assert_eq!(entries[0].premium_request_cost, Some(7.5)); + // Per-model row didn't somehow inherit aggregate AIU. + assert_eq!(entries[0].nano_aiu, None); + } + + #[test] + fn aggregate_credit_guard_ignores_skipped_per_model_rows() { + // Belt-and-suspenders: the aggregate-credit suppression guard + // (`any_per_model_priced_billing`) must mirror the + // `skip_metrics_row` filter applied above when iterating + // model_metrics. Otherwise a per-model row that was skipped (no + // entry emitted) could still suppress the synthetic + // aggregate-credit row, silently dropping the session AIU. + // + // Construct a row that: + // * Has `cost > 0` (would suppress the synthetic under the + // old guard that read raw metrics). + // * Has all 5 tokens = 0 AND `requests.count == 0` AND no + // per-model AIU (so `skip_metrics_row` discards it — no + // entry emitted). + // This shape is unreachable on observed data because + // `requests.cost = count × multiplier` makes + // `count == 0 ⇒ cost == 0`. But the guard's correctness + // shouldn't depend on that schema invariant — if the CLI ever + // emits this shape, the aggregate must survive. + // + // Expected: the per-model row is skipped (not in entries), AND + // the synthetic aggregate-credit row IS emitted (the only + // priced signal for the session). + let (_dir, path) = write_jsonl(&[shutdown_event_with_naiu( + "evt-skipped-cost-with-aggregate", + "2026-05-20T16:01:29.481Z", + json!({ + "claude-opus-4.7-1m-internal": { + "usage": { + "inputTokens": 0u64, + "outputTokens": 0u64, + "cacheReadTokens": 0u64, + "cacheWriteTokens": 0u64, + "reasoningTokens": 0u64 + }, + // count == 0 but cost > 0 — unreachable today but + // exercises the guard's robustness against the + // `count × multiplier` invariant breaking. + "requests": {"count": 0, "cost": 7.5} + } + }), + Some(1_000_000_000), + )]); + let entries = parse_session_state_file(&path).unwrap(); + // The per-model row is skipped — no entry for it. + assert!( + !entries.iter().any(|e| !e.model.is_empty()), + "skipped row (all-zero tokens + count=0 + no AIU) must NOT \ + produce a per-model entry; got {entries:?}" + ); + // The synthetic aggregate-credit MUST survive (the only priced + // signal). Before the fix that iterated raw metrics, the + // skipped row's `cost > 0` would have suppressed this and + // silently dropped the session AIU. + let aggregate = entries + .iter() + .find(|e| e.dedup_key.starts_with("credit-aggregate:")) + .expect("synthetic aggregate-credit must survive a skipped-row with cost > 0"); + assert!(aggregate.model.is_empty()); + assert_eq!(aggregate.nano_aiu, Some(1_000_000_000)); + } + + #[test] + fn aggregate_credit_is_emitted_when_per_model_has_only_tokens() { + // Forward-compat preservation: when per-model rows carry tokens but + // no priced billing (no `requests.cost`, no per-model AIU), the + // aggregate AIU is the only **source-provided** priced signal for + // the session. Emit the synthetic so the AIU isn't silently lost. + // + // Under `--mode auto`, the per-model row is then independently + // token-priced via LiteLLM (since `premium_cost == None` ⇒ + // `has_premium_data == false`, so the Auto dispatch falls through + // to the token-priced arm) AND the synthetic contributes + // `aiu × $0.01` — i.e. the two stack. The stack is accepted + // because the alternative (dropping the aggregate AIU) would + // silently under-count a real charge; see the long comment at + // `parser.rs::parse_session_state_file` for the full rationale. + // The shape is unobserved in the local 200-file corpus. + // + // NOTE: `requests.cost` is OMITTED — not set to 0 — because + // `cost: Some(0.0)` makes `has_premium_data == true` on the loader + // side and routes the per-model row to the premium arm ($0 bill), + // which would silently contradict the "billed via LiteLLM" claim + // above. Pinning the genuinely-absent shape keeps the test honest. + let (_dir, path) = write_jsonl(&[shutdown_event_with_naiu( + "evt-tokens-and-aggregate", + "2026-05-20T16:01:29.481Z", + json!({ + "claude-opus-4.7-1m-internal": { + "usage": { + "inputTokens": 100u64, + "outputTokens": 10u64, + "cacheReadTokens": 0u64, + "cacheWriteTokens": 0u64, + "reasoningTokens": 0u64 + }, + "requests": {"count": 1} + // No per-model totalNanoAiu and `requests.cost` omitted. + } + }), + Some(1_000_000_000), + )]); + let entries = parse_session_state_file(&path).unwrap(); + // Two entries: the per-model row plus the synthetic aggregate. + assert_eq!(entries.len(), 2); + let per_model = entries + .iter() + .find(|e| !e.model.is_empty()) + .expect("per-model entry should be emitted"); + // Locks in that the per-model row carries NO priced billing — so + // Auto really does fall through to LiteLLM token pricing as the + // comment claims, instead of silently hitting the premium-$0 arm. + assert_eq!(per_model.premium_request_cost, None); + assert_eq!(per_model.nano_aiu, None); + let aggregate = entries + .iter() + .find(|e| e.dedup_key.starts_with("credit-aggregate:")) + .expect("synthetic aggregate-credit entry should be emitted"); + assert!(aggregate.model.is_empty()); + assert_eq!(aggregate.nano_aiu, Some(1_000_000_000)); + } + + #[test] + fn aggregate_credit_is_emitted_when_per_model_naiu_is_explicit_zero() { + // Edge improvement over the previous `Option::is_some()` guard: + // a per-model row with `totalNanoAiu = Some(0)` and nothing else + // signals "this model contributed zero AIU." Under the old guard + // that `Some(0)` would have suppressed the synthetic and silently + // dropped the aggregate AIU. Now the synthetic is emitted because + // the per-model row carries no PRICED billing. + let (_dir, path) = write_jsonl(&[shutdown_event_with_naiu( + "evt-zero-aiu-and-aggregate", + "2026-05-20T16:01:29.481Z", + json!({ + "claude-opus-4.7-1m-internal": { + "usage": { + "inputTokens": 0u64, + "outputTokens": 0u64, + "cacheReadTokens": 0u64, + "cacheWriteTokens": 0u64, + "reasoningTokens": 0u64 + }, + "requests": {"count": 0, "cost": 0}, + "totalNanoAiu": 0u64 + } + }), + Some(1_000_000_000), + )]); + let entries = parse_session_state_file(&path).unwrap(); + // The per-model row is skipped by `skip_metrics_row` (all-zero); the + // synthetic aggregate captures the session AIU. + assert_eq!(entries.len(), 1); + assert!(entries[0].dedup_key.starts_with("credit-aggregate:")); + assert_eq!(entries[0].nano_aiu, Some(1_000_000_000)); + } + + #[test] + fn legacy_pre_aiu_schema_yields_none_nano_aiu() { + // 1.0.40-era data: no totalNanoAiu anywhere. Credits remain None, + // not 0 — the caller can distinguish "no credit data" from "zero + // credits". + let (_dir, path) = write_jsonl(&[shutdown_event( + "evt-legacy", + "2026-02-28T09:52:27.352Z", + json!({ + "claude-opus-4.6": { + "usage": { + "inputTokens": 1000u64, + "outputTokens": 100u64, + "cacheReadTokens": 500u64, + "cacheWriteTokens": 0u64, + "reasoningTokens": 0u64 + }, + "requests": {"count": 1, "cost": 1} + } + }), + )]); + let entries = parse_session_state_file(&path).unwrap(); + assert_eq!(entries.len(), 1); + assert_eq!(entries[0].nano_aiu, None); + } } diff --git a/rust/crates/ccusage/src/adapter/copilot/paths.rs b/rust/crates/ccusage/src/adapter/copilot/paths.rs index b6910b4..382f810 100644 --- a/rust/crates/ccusage/src/adapter/copilot/paths.rs +++ b/rust/crates/ccusage/src/adapter/copilot/paths.rs @@ -1,32 +1,414 @@ -use std::{collections::HashSet, env, path::PathBuf}; +use std::{env, path::Path, path::PathBuf}; -use crate::{Result, collect_files_with_extension}; +use crate::Result; -pub(crate) const COPILOT_OTEL_FILE_EXPORTER_PATH_ENV: &str = "COPILOT_OTEL_FILE_EXPORTER_PATH"; +pub(crate) const COPILOT_CONFIG_DIR_ENV: &str = "COPILOT_CONFIG_DIR"; -pub(super) fn paths() -> Result> { - let mut files = Vec::new(); - let mut seen = HashSet::new(); - if let Some(home) = crate::home::home_dir() { - let default_dir = home.join(".copilot").join("otel"); - if default_dir.is_dir() { - collect_files_with_extension(&default_dir, "jsonl", &mut files); +/// Legacy OTel env vars that now only trigger a warning. +pub(crate) const LEGACY_OTEL_ENV_VARS: &[&str] = &[ + "COPILOT_OTEL_FILE_EXPORTER_PATH", + "COPILOT_OTEL_DEDUP", + "COPILOT_PREFER_OTEL", +]; + +const COPILOT_DIR_NAME: &str = ".copilot"; +const SESSION_STATE_DIR_NAME: &str = "session-state"; +const EVENTS_FILENAME: &str = "events.jsonl"; + +pub(super) fn session_state_paths() -> Result> { + let Some(base) = copilot_base_dir() else { + return Ok(Vec::new()); + }; + let session_state_dir = base.join(SESSION_STATE_DIR_NAME); + if !session_state_dir.is_dir() { + return Ok(Vec::new()); + } + Ok(session_state_event_files(&session_state_dir)) +} + +pub(super) fn has_any_session_state_event_file() -> bool { + let Some(base) = copilot_base_dir() else { + return false; + }; + let session_state_dir = base.join(SESSION_STATE_DIR_NAME); + let Ok(entries) = std::fs::read_dir(&session_state_dir) else { + return false; + }; + entries.flatten().any(|entry| { + let path = entry.path(); + path.is_dir() && path.join(EVENTS_FILENAME).is_file() + }) +} + +fn copilot_base_dir() -> Option { + if let Some(value) = env::var_os(COPILOT_CONFIG_DIR_ENV) { + let trimmed_path = PathBuf::from(trim_os_string(&value)); + if !trimmed_path.as_os_str().is_empty() { + return if trimmed_path.is_dir() { + Some(trimmed_path) + } else { + None + }; } } - if let Some(path) = copilot_exporter_path() { - files.push(path); + crate::home::home_dir().map(|home| home.join(COPILOT_DIR_NAME)) +} + +fn trim_os_string(value: &std::ffi::OsStr) -> std::ffi::OsString { + #[cfg(unix)] + { + use std::os::unix::ffi::{OsStrExt, OsStringExt}; + let bytes = value.as_bytes(); + if let Ok(s) = std::str::from_utf8(bytes) { + return std::ffi::OsString::from(s.trim()); + } + let start = bytes + .iter() + .position(|b| !b.is_ascii_whitespace()) + .unwrap_or(bytes.len()); + let end = bytes + .iter() + .rposition(|b| !b.is_ascii_whitespace()) + .map_or(start, |i| i + 1); + std::ffi::OsString::from_vec(bytes[start..end].to_vec()) + } + #[cfg(not(unix))] + { + std::ffi::OsString::from(value.to_string_lossy().trim()) + } +} + +fn session_state_event_files(dir: &Path) -> Vec { + let mut files = Vec::new(); + let Ok(entries) = std::fs::read_dir(dir) else { + return files; + }; + for entry in entries.flatten() { + let path = entry.path(); + if !path.is_dir() { + continue; + } + let events = path.join(EVENTS_FILENAME); + if events.is_file() { + files.push(events); + } } - files.retain(|path| seen.insert(path.clone())); files.sort(); - Ok(files) + files } -fn copilot_exporter_path() -> Option { - let path = env::var(COPILOT_OTEL_FILE_EXPORTER_PATH_ENV).ok()?; - let path = path.trim(); - if path.is_empty() { - return None; +pub(crate) fn legacy_otel_env_vars_in_use() -> Vec<&'static str> { + LEGACY_OTEL_ENV_VARS + .iter() + .copied() + .filter(|name| { + env::var_os(name) + .map(|value| !trim_os_string(&value).is_empty()) + .unwrap_or(false) + }) + .collect() +} + +#[cfg(test)] +mod tests { + use std::ffi::OsStr; + + use ccusage_test_support::{EnvVarGuard, fs_fixture}; + + use super::*; + + fn env_scope(overrides: &[(&'static str, Option<&str>)]) -> EnvVarGuard { + let overrides = overrides + .iter() + .map(|(key, value)| (*key, value.map(OsStr::new))) + .collect::>(); + EnvVarGuard::set_many(&overrides) + } + + #[test] + fn enumerates_session_state_events_files() { + let fixture = fs_fixture!({ + "session-state/aaaa-1111/events.jsonl": "", + "session-state/aaaa-1111/workspace.yaml": "cwd: /tmp\n", + "session-state/bbbb-2222/events.jsonl": "", + "session-state/cccc-3333/events.jsonl": "", + "session-state/dddd-empty/.keep": "", + }); + let _env = env_scope(&[( + COPILOT_CONFIG_DIR_ENV, + Some(fixture.root().to_str().unwrap()), + )]); + + let paths = session_state_paths().unwrap(); + assert_eq!( + paths.len(), + 3, + "expected three events.jsonl entries, got {paths:?}" + ); + for uuid in ["aaaa-1111", "bbbb-2222", "cccc-3333"] { + let expected = fixture.path(format!("session-state/{uuid}/events.jsonl")); + assert!( + paths.contains(&expected), + "missing entry for {uuid} in {paths:?}" + ); + } + } + + #[test] + fn respects_copilot_config_dir_env() { + let fixture = fs_fixture!({ + "session-state/alpha/events.jsonl": "", + // Files under `otel/` exist on disk but must NOT be discovered — + // the OTel source is intentionally ignored after this change. + "otel/trace.jsonl": "", + }); + let _env = env_scope(&[( + COPILOT_CONFIG_DIR_ENV, + Some(fixture.root().to_str().unwrap()), + )]); + + let paths = session_state_paths().unwrap(); + assert_eq!( + paths.len(), + 1, + "expected one session-state events.jsonl, got {paths:?}" + ); + assert!( + paths[0].ends_with("session-state/alpha/events.jsonl"), + "got {paths:?}" + ); + } + + #[test] + fn ignores_otel_directory_even_when_present() { + let fixture = fs_fixture!({ + "otel/trace.jsonl": "{\"type\":\"span\"}", + "otel/nested/another.jsonl": "{\"type\":\"span\"}", + }); + let _env = env_scope(&[( + COPILOT_CONFIG_DIR_ENV, + Some(fixture.root().to_str().unwrap()), + )]); + + // No session-state dir, only an `otel/` dir with files. Discovery + // must return zero paths — OTel is no longer a data source. + let paths = session_state_paths().unwrap(); + assert!( + paths.is_empty(), + "OTel files must not be discovered, got {paths:?}" + ); + } + + #[test] + fn copilot_otel_file_exporter_path_env_is_ignored() { + let fixture = fs_fixture!({ + "explicit-otel.jsonl": "{\"type\":\"span\"}", + }); + let _env = env_scope(&[ + ( + "COPILOT_OTEL_FILE_EXPORTER_PATH", + Some(fixture.path("explicit-otel.jsonl").to_str().unwrap()), + ), + // No session-state dir; the only thing pointed at is the + // legacy OTel exporter env var, which must be ignored. + ( + COPILOT_CONFIG_DIR_ENV, + Some(fixture.root().to_str().unwrap()), + ), + ]); + + let paths = session_state_paths().unwrap(); + assert!( + paths.is_empty(), + "COPILOT_OTEL_FILE_EXPORTER_PATH must be inert, got {paths:?}" + ); + } + + #[test] + fn missing_directories_yield_no_sources() { + let fixture = fs_fixture!({ + ".keep": "", + }); + let _env = env_scope(&[( + COPILOT_CONFIG_DIR_ENV, + Some(fixture.root().to_str().unwrap()), + )]); + + let paths = session_state_paths().unwrap(); + assert!(paths.is_empty(), "expected zero paths, got {paths:?}"); + } + + #[test] + fn nonexistent_copilot_config_dir_does_not_fall_back_to_default() { + // Regression: an explicit `COPILOT_CONFIG_DIR` pointing at a + // directory that doesn't exist must NOT silently fall through to + // `~/.copilot`. The user explicitly chose a different location, + // and reading from the default install would surprise them with + // data they didn't ask for. We instead return an empty Vec so + // `ccusage copilot ...` prints "No usage data found". + // + // Hermetic: override HOME to a temp dir that DOES contain a + // `.copilot/session-state//events.jsonl` fixture. Under a + // buggy implementation that silently fell through to + // `~/.copilot`, the fall-through would find the fixture and the + // assertion would fail; under the correct implementation the + // explicit override wins and the result is empty regardless of + // HOME contents. + let home_fixture = fs_fixture!({ + ".copilot/session-state/sentinel/events.jsonl": + "{\"sentinel\":\"would only be seen if the override silently fell through\"}\n", + }); + let _env = env_scope(&[ + ("HOME", Some(home_fixture.root().to_str().unwrap())), + // Clear Windows alternatives so home_dir() can't pick them up. + ("USERPROFILE", None), + ("HOMEDRIVE", None), + ("HOMEPATH", None), + ( + COPILOT_CONFIG_DIR_ENV, + Some("/definitely/does/not/exist/on/any/test/host"), + ), + ]); + + let paths = session_state_paths().unwrap(); + assert!( + paths.is_empty(), + "explicit override at a nonexistent path must yield zero \ + sources, not silently fall back to ~/.copilot; got {paths:?}" + ); + } + + #[test] + fn legacy_otel_env_vars_in_use_reports_only_set_non_empty_vars() { + // All unset → empty. + let _env = env_scope(&[ + ("COPILOT_OTEL_FILE_EXPORTER_PATH", None), + ("COPILOT_OTEL_DEDUP", None), + ("COPILOT_PREFER_OTEL", None), + ]); + assert!(legacy_otel_env_vars_in_use().is_empty()); + drop(_env); + + // One set → reported. + let _env = env_scope(&[ + ("COPILOT_OTEL_FILE_EXPORTER_PATH", Some("/tmp/x.jsonl")), + ("COPILOT_OTEL_DEDUP", None), + ("COPILOT_PREFER_OTEL", None), + ]); + assert_eq!( + legacy_otel_env_vars_in_use(), + vec!["COPILOT_OTEL_FILE_EXPORTER_PATH"] + ); + drop(_env); + + // All three set → all reported in declaration order. + let _env = env_scope(&[ + ("COPILOT_OTEL_FILE_EXPORTER_PATH", Some("/tmp/x.jsonl")), + ("COPILOT_OTEL_DEDUP", Some("strict")), + ("COPILOT_PREFER_OTEL", Some("1")), + ]); + assert_eq!( + legacy_otel_env_vars_in_use(), + vec![ + "COPILOT_OTEL_FILE_EXPORTER_PATH", + "COPILOT_OTEL_DEDUP", + "COPILOT_PREFER_OTEL", + ] + ); + drop(_env); + + // Whitespace-only value → treated as unset (matches the + // COPILOT_CONFIG_DIR convention in `copilot_base_dir`). + let _env = env_scope(&[ + ("COPILOT_OTEL_FILE_EXPORTER_PATH", Some(" ")), + ("COPILOT_OTEL_DEDUP", None), + ("COPILOT_PREFER_OTEL", None), + ]); + assert!( + legacy_otel_env_vars_in_use().is_empty(), + "whitespace-only value should not count as set" + ); + } + + #[test] + #[cfg(unix)] + fn copilot_config_dir_with_non_utf8_path_is_authoritative_not_silently_dropped() { + // Regression: a non-UTF-8 directory path (legal on Unix) used to + // fall through the `env::var(...).ok()` lossy String conversion + // (`Err(NotUnicode)` → `None`), silently activating the + // `~/.copilot` default — directly contradicting the + // "override is authoritative" invariant documented on + // `copilot_base_dir`. Now reads via `env::var_os` so non-UTF-8 + // values flow through unchanged. + // + // Hermetic: HOME is overridden to a temp dir that DOES contain + // a `.copilot/session-state//events.jsonl` fixture. Under + // the buggy code, the lossy `Err(NotUnicode) → None` path would + // fall through to `~/.copilot` (= temp dir here), find the + // fixture, and return a non-empty Vec — failing the assertion. + // Under the fixed code the non-UTF-8 override is honored and + // points at a nonexistent directory, so the result is empty. + use std::ffi::OsString; + use std::os::unix::ffi::OsStringExt; + + let home_fixture = fs_fixture!({ + ".copilot/session-state/sentinel/events.jsonl": + "{\"sentinel\":\"would only be seen if the override silently fell through\"}\n", + }); + let _env = env_scope(&[ + ("HOME", Some(home_fixture.root().to_str().unwrap())), + ("USERPROFILE", None), + ("HOMEDRIVE", None), + ("HOMEPATH", None), + // Clear here so the guard captures the prior value and restores it + // after the direct non-UTF-8 `set_var` below. + (COPILOT_CONFIG_DIR_ENV, None), + ]); + let mut non_utf8 = b"/tmp/ccusage-test-".to_vec(); + non_utf8.extend_from_slice(b"\xff\xfe-non-utf8-dir-does-not-exist"); + let override_value = OsString::from_vec(non_utf8); + unsafe { env::set_var(COPILOT_CONFIG_DIR_ENV, &override_value) }; + + let paths = session_state_paths().unwrap(); + assert!( + paths.is_empty(), + "non-UTF-8 override at a nonexistent path must be honored as an \ + explicit override (yielding zero sources), not coerced to \ + 'env unset' and silently fall back to ~/.copilot; got {paths:?}" + ); + } + + #[test] + #[cfg(unix)] + fn legacy_otel_env_var_with_non_utf8_value_is_still_reported() { + // Regression mirror of the `env::var` → `env::var_os` fix in + // `copilot_base_dir`: if a user (or test harness) sets one of + // the deprecated OTel env vars to a non-UTF-8 byte sequence, + // the deprecation warning MUST still fire. The previous + // `env::var(name).ok()` flow would silently coerce + // `Err(NotUnicode)` to `None` and report the var as unset. + use std::ffi::OsString; + use std::os::unix::ffi::OsStringExt; + + let _env = env_scope(&[ + ("COPILOT_OTEL_FILE_EXPORTER_PATH", None), + ("COPILOT_OTEL_DEDUP", None), + ("COPILOT_PREFER_OTEL", None), + ]); + let mut non_utf8 = b"/tmp/otel-".to_vec(); + non_utf8.extend_from_slice(b"\xff\xfe-non-utf8.jsonl"); + unsafe { + env::set_var( + "COPILOT_OTEL_FILE_EXPORTER_PATH", + OsString::from_vec(non_utf8), + ) + }; + + assert_eq!( + legacy_otel_env_vars_in_use(), + vec!["COPILOT_OTEL_FILE_EXPORTER_PATH"], + "non-UTF-8 value must still be detected as set (deprecation \ + warning would otherwise silently skip it)", + ); } - let path = PathBuf::from(path); - path.is_file().then_some(path) } diff --git a/rust/crates/ccusage/src/config.rs b/rust/crates/ccusage/src/config.rs index 5eba273..ca23a0e 100644 --- a/rust/crates/ccusage/src/config.rs +++ b/rust/crates/ccusage/src/config.rs @@ -655,7 +655,7 @@ impl From for CostMode { fn from(value: ConfigCostMode) -> Self { match value { ConfigCostMode::Auto => Self::Auto, - ConfigCostMode::Calculate => Self::Calculate, + ConfigCostMode::Calculate | ConfigCostMode::Api => Self::Calculate, ConfigCostMode::Display => Self::Display, } } diff --git a/rust/crates/ccusage/src/config_schema.rs b/rust/crates/ccusage/src/config_schema.rs index ccf4fc7..2ef77d1 100644 --- a/rust/crates/ccusage/src/config_schema.rs +++ b/rust/crates/ccusage/src/config_schema.rs @@ -489,6 +489,25 @@ pub(crate) enum ConfigCostMode { Auto, Calculate, Display, + // Discoverability alias for `Calculate` — both bill from LiteLLM token + // pricing. Surfaces as `"api"` in the JSON schema enum so users can + // name the api-equivalent intent explicitly without expanding the + // `CostMode` enum. + // + // This is a **global** alias, not Copilot-scoped: setting + // `--mode api` (or `mode: "api"` in config) works for every agent + // (Claude, Codex, Amp, Copilot, etc.) and means the same thing + // everywhere — "compute from token counts via LiteLLM, never from + // any source-precomputed cost." The motivation for adding it was to + // give Copilot users an obvious way to contrast `auto`'s + // "what GitHub billed" with the equivalent if they had gone direct + // to the provider's API, but the semantics generalise cleanly so + // exposing it globally is intentional rather than a leak. + // + // No doc-comment (only line comments) here so schemars keeps the + // variant inside the flat enum rather than splitting it into a + // separate `oneOf` arm. + Api, } #[derive(Clone, Copy, Debug, Deserialize, JsonSchema)] diff --git a/rust/crates/ccusage/src/snapshots/ccusage__config_schema__tests__snapshots_schema_agent_specific_option_edges.snap b/rust/crates/ccusage/src/snapshots/ccusage__config_schema__tests__snapshots_schema_agent_specific_option_edges.snap index 63c1dc8..ab2d41a 100644 --- a/rust/crates/ccusage/src/snapshots/ccusage__config_schema__tests__snapshots_schema_agent_specific_option_edges.snap +++ b/rust/crates/ccusage/src/snapshots/ccusage__config_schema__tests__snapshots_schema_agent_specific_option_edges.snap @@ -151,7 +151,8 @@ expression: "json!({\n \"rootRef\": schema[\"$ref\"], \"rootProperties\":\n "enum": [ "auto", "calculate", - "display" + "display", + "api" ], "markdownDescription": "Cost calculation mode.", "type": "string" @@ -331,7 +332,8 @@ expression: "json!({\n \"rootRef\": schema[\"$ref\"], \"rootProperties\":\n "enum": [ "auto", "calculate", - "display" + "display", + "api" ], "markdownDescription": "Cost calculation mode.", "type": "string" @@ -496,7 +498,8 @@ expression: "json!({\n \"rootRef\": schema[\"$ref\"], \"rootProperties\":\n "enum": [ "auto", "calculate", - "display" + "display", + "api" ], "markdownDescription": "Cost calculation mode.", "type": "string" @@ -668,7 +671,8 @@ expression: "json!({\n \"rootRef\": schema[\"$ref\"], \"rootProperties\":\n "enum": [ "auto", "calculate", - "display" + "display", + "api" ], "markdownDescription": "Cost calculation mode.", "type": "string" @@ -833,7 +837,8 @@ expression: "json!({\n \"rootRef\": schema[\"$ref\"], \"rootProperties\":\n "enum": [ "auto", "calculate", - "display" + "display", + "api" ], "markdownDescription": "Cost calculation mode.", "type": "string" @@ -1003,7 +1008,8 @@ expression: "json!({\n \"rootRef\": schema[\"$ref\"], \"rootProperties\":\n "enum": [ "auto", "calculate", - "display" + "display", + "api" ], "markdownDescription": "Cost calculation mode.", "type": "string"