70 lines
3.4 KiB
JavaScript
70 lines
3.4 KiB
JavaScript
// Token-Verbrauch eines Issues aus den Claude-Code-Protokollen (~/.claude/projects/**/*.jsonl).
|
|
// Zuordnung über den Branch: Claude Code schreibt zu jedem Eintrag den aktuellen Branch (gitBranch)
|
|
// und das Arbeitsverzeichnis (cwd). Gezählt wird jede Antwort einmal, Subagenten eingeschlossen.
|
|
// Aufruf: node .claude/skills/aufgabe-abschliessen/tokens.mjs [<branch>] (oder: make tokens)
|
|
import { readdirSync, readFileSync, statSync } from 'node:fs';
|
|
import { execSync } from 'node:child_process';
|
|
import { homedir } from 'node:os';
|
|
import { basename, join } from 'node:path';
|
|
|
|
const git = (cmd) => execSync(`git ${cmd}`, { encoding: 'utf8' }).trim();
|
|
const branch = process.argv[2] || git('branch --show-current');
|
|
const repo = basename(git('rev-parse --show-toplevel'));
|
|
const root = join(process.env.CLAUDE_CONFIG_DIR || join(homedir(), '.claude'), 'projects');
|
|
|
|
function* jsonlFiles(dir) {
|
|
for (const name of readdirSync(dir)) {
|
|
const p = join(dir, name);
|
|
if (statSync(p).isDirectory()) yield* jsonlFiles(p);
|
|
else if (name.endsWith('.jsonl')) yield p;
|
|
}
|
|
}
|
|
|
|
const inRepo = (cwd = '') => cwd.split(/[\\/]/).includes(repo);
|
|
const answers = new Map(); // Antwort-ID -> Eintrag; eine Antwort steht oft mehrfach im Protokoll
|
|
for (const file of jsonlFiles(root)) {
|
|
for (const line of readFileSync(file, 'utf8').split('\n')) {
|
|
if (!line.includes('"usage"') || !line.includes(branch)) continue;
|
|
let e;
|
|
try { e = JSON.parse(line); } catch { continue; }
|
|
const m = e.message;
|
|
if (e.type !== 'assistant' || !m?.usage || m.model === '<synthetic>') continue;
|
|
if (e.gitBranch !== branch || !inRepo(e.cwd)) continue;
|
|
const id = m.id || e.requestId || e.uuid;
|
|
// Teilstände beim Streaming: den Eintrag mit dem höchsten Output behalten
|
|
if ((answers.get(id)?.output_tokens ?? -1) >= (m.usage.output_tokens ?? 0)) continue;
|
|
answers.set(id, { ...m.usage, model: m.model, session: e.sessionId, time: e.timestamp });
|
|
}
|
|
}
|
|
|
|
if (answers.size === 0) {
|
|
console.error(`Keine Einträge für Branch "${branch}" in ${root}.`);
|
|
console.error('Gezählt wird nur, was in einer Sitzung im Repo-Root auf diesem Branch lief. Sonst Token im Abschlusskommentar als "nicht ermittelt" angeben.');
|
|
process.exit(1);
|
|
}
|
|
|
|
const sum = { calls: 0, input: 0, output: 0, cacheWrite: 0, cacheRead: 0 };
|
|
const perModel = {};
|
|
const sessions = new Set();
|
|
const times = [];
|
|
for (const a of answers.values()) {
|
|
const s = (perModel[a.model] ??= { calls: 0, input: 0, output: 0, cacheWrite: 0, cacheRead: 0 });
|
|
for (const t of [s, sum]) {
|
|
t.calls += 1;
|
|
t.input += a.input_tokens || 0;
|
|
t.output += a.output_tokens || 0;
|
|
t.cacheWrite += a.cache_creation_input_tokens || 0;
|
|
t.cacheRead += a.cache_read_input_tokens || 0;
|
|
}
|
|
sessions.add(a.session);
|
|
times.push(a.time);
|
|
}
|
|
times.sort();
|
|
|
|
const fmt = (n) => (n >= 1e6 ? `${(n / 1e6).toFixed(1).replace('.', ',')}M` : `${Math.round(n / 1e3)}k`);
|
|
const line = (t) => `${t.calls} Aufrufe, ~${fmt(t.input)} Input, ~${fmt(t.output)} Output, ~${fmt(t.cacheWrite)} Cache-Write, ~${fmt(t.cacheRead)} Cache-Read`;
|
|
|
|
console.log(`Branch ${branch}: ${sessions.size} Sitzung(en), ${times[0]} bis ${times.at(-1)}`);
|
|
for (const [model, t] of Object.entries(perModel)) console.log(`- ${model}: ${line(t)}`);
|
|
console.log(`\nFür den Abschlusskommentar:\nClaude Code (${Object.keys(perModel).join(', ')}): ~${fmt(sum.output)} Output, ~${fmt(sum.cacheWrite)} Cache-Write, ~${fmt(sum.cacheRead)} Cache-Read`);
|