Skip to content

an open-source alternative to the dots, bots and muses of the world, run an office of claude code/codex like agents on your laptop, sandboxes or anywhere, uses your existing subscriptions

feat(telemetry): read real token usage + est. cost from CC transcripts

Chaitanya Giri1a231b5fcc91
diff --git a/src/main/index.ts b/src/main/index.ts
index b8771c77..33fffcdb 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -15,6 +15,7 @@ import { HiveManager, type AgentMeta, type HiveMessage } from './hive';
import { HookServer } from './hooks';
import { MemoryManager } from './memory';
import { enrichMessage } from './assistant';
+import { readAgentUsage } from './transcript';
const isDev = !!process.env.ELECTRON_RENDERER_URL;
const ptyManager = new PtyManager();
@@ -302,6 +303,10 @@ ipcMain.handle('app:resetAll', () => {
app.exit(0);
});
+// ─── IPC: token telemetry (real usage + est. cost from CC transcripts) ───────
+ipcMain.handle('hive:agentUsage', (_evt, cwd: unknown) =>
+ typeof cwd === 'string' ? readAgentUsage(cwd) : null);
+
app.whenReady().then(() => {
// Bootstrap the hive (if harnessHome is configured) and start the message router.
if (hive.enabled()) {
diff --git a/src/main/transcript.ts b/src/main/transcript.ts
new file mode 100644
index 00000000..3dcccdc8
--- /dev/null
+++ b/src/main/transcript.ts
@@ -0,0 +1,78 @@
+import { existsSync, readdirSync, readFileSync } from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+
+/** Resolve the Claude Code transcript directory for a given working directory.
+ * Claude Code stores per-project transcripts under ~/.claude/projects, keying
+ * each project by its absolute cwd with the leading slash dropped and every
+ * remaining slash turned into a dash (e.g. /Users/me/app → Users-me-app). */
+export function projectDir(cwd: string): string {
+ return path.join(os.homedir(), '.claude/projects', cwd.replace(/^\//, '').replaceAll('/', '-'));
+}
+
+export interface AgentUsage {
+ inputTokens: number;
+ outputTokens: number;
+ cacheReadTokens: number;
+ cacheWriteTokens: number;
+ estimatedCostUsd: number;
+}
+
+// Sonnet pricing, USD per million tokens.
+const PRICE_INPUT_PER_M = 3;
+const PRICE_OUTPUT_PER_M = 15;
+const PRICE_CACHE_READ_PER_M = 0.3;
+const PRICE_CACHE_WRITE_PER_M = 3.75;
+
+function zero(): AgentUsage {
+ return { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0, estimatedCostUsd: 0 };
+}
+
+/** Sum real token usage across every Claude Code transcript for `cwd` and
+ * estimate the dollar cost using Sonnet pricing. Resilient by design: any
+ * unreadable file or malformed line is skipped, and any unexpected failure
+ * yields a zeroed result rather than throwing into the IPC handler. */
+export function readAgentUsage(cwd: string): AgentUsage {
+ const usage = zero();
+ try {
+ const dir = projectDir(cwd);
+ if (!existsSync(dir)) return usage;
+ const files = readdirSync(dir).filter((f) => f.endsWith('.jsonl'));
+ for (const file of files) {
+ try {
+ const text = readFileSync(path.join(dir, file), 'utf8');
+ for (const line of text.split('\n')) {
+ const trimmed = line.trim();
+ if (!trimmed) continue;
+ let rec: { type?: unknown; message?: { usage?: Record<string, unknown> } };
+ try {
+ rec = JSON.parse(trimmed);
+ } catch {
+ continue;
+ }
+ if (rec.type !== 'assistant') continue;
+ const u = rec.message?.usage;
+ if (!u) continue;
+ usage.inputTokens += num(u.input_tokens);
+ usage.outputTokens += num(u.output_tokens);
+ usage.cacheWriteTokens += num(u.cache_creation_input_tokens);
+ usage.cacheReadTokens += num(u.cache_read_input_tokens);
+ }
+ } catch {
+ // Skip this file; keep accumulating across the rest.
+ }
+ }
+ usage.estimatedCostUsd =
+ (usage.inputTokens / 1_000_000) * PRICE_INPUT_PER_M +
+ (usage.outputTokens / 1_000_000) * PRICE_OUTPUT_PER_M +
+ (usage.cacheReadTokens / 1_000_000) * PRICE_CACHE_READ_PER_M +
+ (usage.cacheWriteTokens / 1_000_000) * PRICE_CACHE_WRITE_PER_M;
+ return usage;
+ } catch {
+ return zero();
+ }
+}
+
+function num(v: unknown): number {
+ return typeof v === 'number' && Number.isFinite(v) ? v : 0;
+}
diff --git a/src/preload/index.ts b/src/preload/index.ts
index 42e5960a..83d00ddf 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -96,6 +96,16 @@ export interface GitCommit {
export interface GitStatusEntry { path: string; index: string; worktree: string }
export interface GitStatus { staged: GitStatusEntry[]; unstaged: GitStatusEntry[]; untracked: string[] }
+/** Real token usage + estimated USD cost summed from an agent's Claude Code
+ * transcripts under ~/.claude/projects (Sonnet pricing). */
+export interface AgentUsage {
+ inputTokens: number;
+ outputTokens: number;
+ cacheReadTokens: number;
+ cacheWriteTokens: number;
+ estimatedCostUsd: number;
+}
+
const api = {
version: '0.1.0',
@@ -219,7 +229,13 @@ const api = {
// ─── Reset ─────────────────────────────────────────────────────────────────
/** Wipe all hive data + the memory palace, reset config, and relaunch the app
* into onboarding. The process exits, so this promise never resolves. */
- resetAll: (): Promise<void> => ipcRenderer.invoke('app:resetAll')
+ resetAll: (): Promise<void> => ipcRenderer.invoke('app:resetAll'),
+
+ // ─── Token telemetry (real usage + est. cost from CC transcripts) ──────────
+ /** Sum input/output/cache tokens + estimated USD cost for an agent from its
+ * Claude Code transcripts. Returns null for an invalid cwd. */
+ agentUsage: (cwd: string): Promise<AgentUsage | null> =>
+ ipcRenderer.invoke('hive:agentUsage', cwd)
};
contextBridge.exposeInMainWorld('cth', api);