Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

claudeUsage.ts

110 lines4.1 KB

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): UsageRecord | null {
24 let parsed: unknown;
25 try {
26 parsed = JSON.parse(line);
27 } catch {
28 return null;
29 }
30 return parseClaudeRecord(parsed);
32​
33function parseClaudeRecord(parsed: unknown): UsageRecord | null {
34 if (typeof parsed !== "object" || parsed === null) return null;
35​
36 const record = parsed as Record<string, unknown>;
37 if (record["type"] !== "assistant") return null;
38​
39 const message = record["message"];
40 if (typeof message !== "object" || message === null) return null;
41 const messageRecord = message as Record<string, unknown>;
42​
43 const usage = messageRecord["usage"];
44 if (typeof usage !== "object" || usage === null) return null;
45 const usageRecord = usage as Record<string, unknown>;
46​
47 const timestampMs = parseTimestampMs(record["timestamp"]);
48 if (timestampMs === null) return null;
49​
50 const model = typeof messageRecord["model"] === "string" ? messageRecord["model"] : "";
51 if (model.length === 0 || model === CLAUDE_SYNTHETIC_MODEL) return null;
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 return {
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 };
78​
79const orEmpty = (record: UsageRecord | null): readonly UsageRecord[] =>
80 record === null ? [] : [record];
81​
82export const claudeUsageFormat: TranscriptUsageFormat<void> = {
83 selectFields: {
84 type: true,
85 timestamp: true,
86 requestId: true,
87 sessionId: true,
88 costUSD: true,
89 message: { id: true, model: true, usage: true },
90 },
91 usageMarkers: ['"usage"'],
92 parseLine: (line) => orEmpty(parseClaudeLine(line)),
93 parseProjected: (projected) => orEmpty(parseClaudeRecord(projected)),
94};
95​
96export const claudeUsageReader: ProviderUsageReader<ClaudeSettings, Path.Path> = {
97 kind: "transcripts",
98 provider: "claude",
99 format: claudeUsageFormat,
100 directories: Effect.fn("claudeUsageReader.directories")(function* ({ config, environment }) {
101 if (config === undefined) return [];
102 const path = yield* Path.Path;
103 const homeDirectory = yield* HostProcess.HomeDirectory;
104 const configured = config.homePath.trim();
105 const home = configured
106 ? expandHomePath(configured, homeDirectory)
107 : environment.CLAUDE_CONFIG_DIR?.trim() || path.join(homeDirectory, ".claude");
108 return [{ dir: path.resolve(home, "projects") }];
109 }),
110};