#!/usr/bin/env python3 """Per-profile token spend + fixed prompt size. Read-only. Sources: each profile's logs/agent.log* "API call #" lines and `hermes -p prompt-size --platform telegram --json` (offline, no API call). Output: /ham.json (default ~/.hermes/cache/scratch/ajan-analiz) Usage: python3 token_usage_from_logs.py [outdir] Exclude other people's profiles (EXCLUDE) before traversal.""" import json, re, subprocess, glob, sys from pathlib import Path from collections import defaultdict from datetime import datetime, timedelta H = Path.home() / '.hermes' OUT = Path(sys.argv[1]) if len(sys.argv) > 1 else H / 'cache/scratch/ajan-analiz' OUT.mkdir(parents=True, exist_ok=True) EXCLUDE = set() # add other people's / isolated profile names here profiles = ['default'] + sorted(p.name for p in (H / 'profiles').iterdir() if p.is_dir() and p.name not in EXCLUDE) def pdir(p): return H if p == 'default' else H / 'profiles' / p def size(f): try: return f.stat().st_size except OSError: return 0 # cache=/ and write= are optional; verify the regex matches 100% of lines on one log first RX = re.compile(r'^(\d{4}-\d\d-\d\d) (\d\d:\d\d:\d\d),\d+ INFO \[([^\]]+)\] agent\.conversation_loop: API call #\d+: model=(\S+) provider=(\S+) in=(\d+) out=(\d+) total=\d+.*?(?:cache=(\d+)/\d+ \(\d+%\))?(?: write=(\d+))?(?: id=|$)') since7 = str(datetime.now().date() - timedelta(days=6)) res = {} for p in profiles: d = pdir(p); r = {'profile': p} r['SOUL.md'] = size(d / 'SOUL.md'); r['MEMORY.md'] = size(d / 'memories/MEMORY.md'); r['USER.md'] = size(d / 'memories/USER.md') sk = glob.glob(str(d / 'skills/**/SKILL.md'), recursive=True) r['skill_count'] = len(sk); r['skill_bytes'] = sum(size(Path(f)) for f in sk) try: cmd = ['hermes'] + ([] if p == 'default' else ['-p', p]) + ['prompt-size', '--platform', 'telegram', '--json'] o = subprocess.run(cmd, capture_output=True, text=True, timeout=90).stdout r['prompt'] = json.loads(o[o.index('{'):]) except Exception as e: r['prompt_error'] = str(e)[:120] day = defaultdict(lambda: defaultdict(int)); model = defaultdict(int); sess = defaultdict(lambda: [0, 0, 0]) for lf in sorted(glob.glob(str(d / 'logs/agent.log*'))): try: for line in open(lf, errors='replace'): if 'API call #' not in line: continue m = RX.match(line) if not m: continue dt, _, s, mdl, _, i, o_, c, w = m.groups() i, o_, c, w = int(i), int(o_), int(c or 0), int(w or 0) g = day[dt]; g['calls'] += 1; g['in'] += i; g['out'] += o_; g['cache'] += c; g['write'] += w; g['fresh'] += max(i - c - w, 0) if dt >= since7: model[mdl] += i + o_ x = sess[s]; x[0] += 1; x[1] = max(x[1], i); x[2] += i except OSError: pass r['daily'] = {k: dict(v) for k, v in sorted(day.items())} r['model_7d'] = dict(model) r['top_sessions'] = [{'session': k, 'calls': v[0], 'max_in': v[1], 'sum_in': v[2]} for k, v in sorted(sess.items(), key=lambda x: -x[1][2])[:3]] res[p] = r print(p, 'ok', file=sys.stderr) json.dump(res, open(OUT / 'ham.json', 'w'), ensure_ascii=False, indent=1) print('done', len(res), OUT / 'ham.json')