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