Open History to see the last commit
1import type { ClaudeSettings } from "@t3tools/contracts";
2import * as Effect from "effect/Effect";
3import * as Path from "effect/Path";
4
5import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
6import {
7 parseTimestampMs,
8 tokenCount,
9 type ProviderUsageReader,
10 type TranscriptUsageFormat,
11 type UsageRecord,
12} from "@t3tools/provider-core/server/usage";
13import * as HostProcess from "@t3tools/shared/HostProcess";
14
15// Claude Code uses this model for local placeholders that never reached the API.
16export const CLAUDE_SYNTHETIC_MODEL = "<synthetic>";
17
18/**
19 * T3 Code writes one record per assistant *content block*, and every one of those records repeats
20 * the same complete `usage` object for the parent message. Summing them overcounts by roughly
21 * 2.4x on a real workload, so the caller must drop repeats by `dedupeKey` and keep the first.
22 */
23export function parseClaudeLine(line: string): readonly UsageRecord[] {
24 let parsed: unknown;
25 try {
26 parsed = JSON.parse(line);
27 } catch {
28 return [];
29 }
30 return parseClaudeRecord(parsed);
31}
32
33function parseClaudeRecord(parsed: unknown): readonly UsageRecord[] {
34 if (typeof parsed !== "object" || parsed === null) return [];
35
36 const record = parsed as Record<string, unknown>;
37 if (record["type"] !== "assistant") return [];
38
39 const message = record["message"];
40 if (typeof message !== "object" || message === null) return [];
41 const messageRecord = message as Record<string, unknown>;
42
43 const usage = messageRecord["usage"];
44 if (typeof usage !== "object" || usage === null) return [];
45 const usageRecord = usage as Record<string, unknown>;
46
47 const timestampMs = parseTimestampMs(record["timestamp"]);
48 if (timestampMs === null) return [];
49
50 const model = typeof messageRecord["model"] === "string" ? messageRecord["model"] : "";
51 if (model.length === 0 || model === CLAUDE_SYNTHETIC_MODEL) return [];
52
53 const messageId = typeof messageRecord["id"] === "string" ? messageRecord["id"] : null;
54 const requestId = typeof record["requestId"] === "string" ? record["requestId"] : null;
55 const dedupeKey =
56 messageId === null && requestId === null ? null : `${messageId ?? ""}:${requestId ?? ""}`;
57
58 const cost = record["costUSD"];
59
60 const executor: UsageRecord = {
61 provider: "claude",
62 timestampMs,
63 model,
64 sessionId: typeof record["sessionId"] === "string" ? record["sessionId"] : "",
65 totals: {
66 uncachedInputTokens: tokenCount(usageRecord["input_tokens"]),
67 cachedInputTokens: tokenCount(usageRecord["cache_read_input_tokens"]),
68 cacheCreationTokens: tokenCount(usageRecord["cache_creation_input_tokens"]),
69 outputTokens: tokenCount(usageRecord["output_tokens"]),
70 // Anthropic folds thinking tokens into output and does not break them out.
71 reasoningTokens: 0,
72 },
73 reportedCostUsd: typeof cost === "number" && Number.isFinite(cost) ? cost : null,
74 speed: usageRecord["speed"] === "fast" ? "fast" : "standard",
75 dedupeKey,
76 };
77
78 // Top-level `usage` is the executor's alone. Advisor calls run on another model at its own rates
79 // and appear only in `iterations`, so each one is its own record under that model.
80 const records = [executor];
81 const iterations: readonly unknown[] = Array.isArray(usageRecord["iterations"])
82 ? usageRecord["iterations"]
83 : [];
84 for (const [index, iteration] of iterations.entries()) {
85 if (typeof iteration !== "object" || iteration === null) continue;
86 const advisor = iteration as Record<string, unknown>;
87 if (advisor["type"] !== "advisor_message") continue;
88
89 const advisorModel = typeof advisor["model"] === "string" ? advisor["model"] : "";
90 if (advisorModel.length === 0 || advisorModel === CLAUDE_SYNTHETIC_MODEL) continue;
91
92 records.push({
93 provider: "claude",
94 timestampMs,
95 model: advisorModel,
96 sessionId: executor.sessionId,
97 totals: {
98 uncachedInputTokens: tokenCount(advisor["input_tokens"]),
99 cachedInputTokens: tokenCount(advisor["cache_read_input_tokens"]),
100 cacheCreationTokens: tokenCount(advisor["cache_creation_input_tokens"]),
101 outputTokens: tokenCount(advisor["output_tokens"]),
102 reasoningTokens: 0,
103 },
104 reportedCostUsd: null,
105 speed: executor.speed,
106 dedupeKey: dedupeKey === null ? null : `${dedupeKey}:advisor:${index}`,
107 });
108 }
109 return records;
110}
111
112export const claudeUsageFormat: TranscriptUsageFormat<void> = {
113 selectFields: {
114 type: true,
115 timestamp: true,
116 requestId: true,
117 sessionId: true,
118 costUSD: true,
119 message: { id: true, model: true, usage: true },
120 },
121 usageMarkers: ['"usage"'],
122 parseLine: (line) => parseClaudeLine(line),
123 parseProjected: (projected) => parseClaudeRecord(projected),
124};
125
126export const claudeUsageReader: ProviderUsageReader<ClaudeSettings, Path.Path> = {
127 kind: "transcripts",
128 provider: "claude",
129 format: claudeUsageFormat,
130 directories: Effect.fn("claudeUsageReader.directories")(function* ({ config, environment }) {
131 if (config === undefined) return [];
132 const path = yield* Path.Path;
133 const homeDirectory = yield* HostProcess.HomeDirectory;
134 const configured = config.homePath.trim();
135 const home = configured
136 ? expandHomePath(configured, homeDirectory)
137 : environment.CLAUDE_CONFIG_DIR?.trim() || path.join(homeDirectory, ".claude");
138 return [{ dir: path.resolve(home, "projects") }];
139 }),
140};