Open History to see the last commit
1/**
2 * Usage history for Claude Code: the transcript format of its
3 * `<home>/projects/**.jsonl` session files and where each instance keeps them.
4 *
5 * @module provider/Drivers/claudeUsage
6 */
7
8import type { ClaudeSettings } from "@t3tools/contracts";
9import * as Effect from "effect/Effect";
10import * as Path from "effect/Path";
11
12import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
13import {
14 parseTimestampMs,
15 tokenCount,
16 type ProviderUsageReader,
17 type TranscriptUsageFormat,
18 type UsageRecord,
19} from "@t3tools/provider-core/server/usage";
20import * as HostProcess from "@t3tools/shared/HostProcess";
21
22/**
23 * Parses one line of a Claude Code transcript.
24 *
25 * T3 Code writes one record per assistant *content block*, and every one of
26 * those records repeats the same complete `usage` object for the parent
27 * message. Summing them overcounts by roughly 2.4x on a real workload, so the
28 * caller must drop repeats by `dedupeKey` and keep the first.
29 */
30export function parseClaudeLine(line: string): UsageRecord | null {
31 let parsed: unknown;
32 try {
33 parsed = JSON.parse(line);
34 } catch {
35 return null;
36 }
37 return parseClaudeRecord(parsed);
38}
39
40function parseClaudeRecord(parsed: unknown): UsageRecord | null {
41 if (typeof parsed !== "object" || parsed === null) return null;
42
43 const record = parsed as Record<string, unknown>;
44 if (record["type"] !== "assistant") return null;
45
46 const message = record["message"];
47 if (typeof message !== "object" || message === null) return null;
48 const messageRecord = message as Record<string, unknown>;
49
50 const usage = messageRecord["usage"];
51 if (typeof usage !== "object" || usage === null) return null;
52 const usageRecord = usage as Record<string, unknown>;
53
54 const timestampMs = parseTimestampMs(record["timestamp"]);
55 if (timestampMs === null) return null;
56
57 const model = typeof messageRecord["model"] === "string" ? messageRecord["model"] : "";
58 if (model.length === 0) return null;
59
60 const messageId = typeof messageRecord["id"] === "string" ? messageRecord["id"] : null;
61 const requestId = typeof record["requestId"] === "string" ? record["requestId"] : null;
62 // Matches ccusage: prefer the message/request pair, fall back to whichever
63 // half exists. Records with neither cannot be de-duplicated.
64 const dedupeKey =
65 messageId === null && requestId === null ? null : `${messageId ?? ""}:${requestId ?? ""}`;
66
67 const cost = record["costUSD"];
68
69 return {
70 provider: "claude",
71 timestampMs,
72 model,
73 sessionId: typeof record["sessionId"] === "string" ? record["sessionId"] : "",
74 totals: {
75 uncachedInputTokens: tokenCount(usageRecord["input_tokens"]),
76 cachedInputTokens: tokenCount(usageRecord["cache_read_input_tokens"]),
77 cacheCreationTokens: tokenCount(usageRecord["cache_creation_input_tokens"]),
78 outputTokens: tokenCount(usageRecord["output_tokens"]),
79 // Anthropic folds thinking tokens into output and does not break them out.
80 reasoningTokens: 0,
81 },
82 reportedCostUsd: typeof cost === "number" && Number.isFinite(cost) ? cost : null,
83 speed: usageRecord["speed"] === "fast" ? "fast" : "standard",
84 dedupeKey,
85 };
86}
87
88const orEmpty = (record: UsageRecord | null): readonly UsageRecord[] =>
89 record === null ? [] : [record];
90
91export const claudeUsageFormat: TranscriptUsageFormat<void> = {
92 // Keeps the dedupe and cost metadata. The `usage` subtree keeps future token fields.
93 selectFields: {
94 type: true,
95 timestamp: true,
96 requestId: true,
97 sessionId: true,
98 costUSD: true,
99 message: { id: true, model: true, usage: true },
100 },
101 usageMarkers: ['"usage"'],
102 parseLine: (line) => orEmpty(parseClaudeLine(line)),
103 parseProjected: (projected) => orEmpty(parseClaudeRecord(projected)),
104};
105
106export const claudeUsageReader: ProviderUsageReader<ClaudeSettings, Path.Path> = {
107 kind: "transcripts",
108 provider: "claude",
109 format: claudeUsageFormat,
110 directories: Effect.fn("claudeUsageReader.directories")(function* ({ config, environment }) {
111 // An undecodable config has no trustworthy home to read.
112 if (config === undefined) return [];
113 const path = yield* Path.Path;
114 const homeDirectory = yield* HostProcess.HomeDirectory;
115 const configured = config.homePath.trim();
116 const home = configured
117 ? expandHomePath(configured, homeDirectory)
118 : environment.CLAUDE_CONFIG_DIR?.trim() || path.join(homeDirectory, ".claude");
119 return [{ dir: path.resolve(home, "projects") }];
120 }),
121};