PR CI / ledger (pull_request) Successful in 4s
PR CI / flow (pull_request) Successful in 4s
PR CI / test (stable) (pull_request) Successful in 38s
PR CI / test (lowest) (pull_request) Successful in 42s
PR CI / security (pull_request) Successful in 48s
PR CI / pr-ci (pull_request) Successful in 2s
PR CI / release-automerge (pull_request) Successful in 4s
140 lines
5.3 KiB
Python
Executable File
140 lines
5.3 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""Adds up the exact tokens of one or more Hermes sessions, for TOKENS.md.
|
|
|
|
Companion to `dev/token-usage.py` (which reads a Claude Code session log). This script is for work
|
|
done by a Hermes agent (any of the Aristocats): Hermes keeps its sessions in its own SQLite file,
|
|
`~/.hermes/state.db`, and has no `.jsonl` log, so a TOKENS.md row for Hermes work comes from this
|
|
script, never from a guess.
|
|
|
|
Usage: dev/token-usage-hermes.py SESSION_ID [SESSION_ID ...] [--include-children]
|
|
[--state-db PATH] [--date 2026-12-04]
|
|
[--row "Wat er is gemaakt" [--version v0.2.0]] [--hours 1.5]
|
|
|
|
Pass every session that did the work: the session of the agent itself and, with --include-children,
|
|
every session it started (a helper agent has `parent_session_id` set, also through several levels).
|
|
Helper agents are part of the work: their tokens are added to the row.
|
|
|
|
Like `dev/token-usage.py`, the row is made per model, because the price differs per model: when the
|
|
helper sessions ran on another model than the main session there is one row for each, the model with
|
|
the most steps first, and the hours are on the first row only.
|
|
|
|
There is no reliable signal for the time worked in state.db, so this script never invents the hours:
|
|
give them with --hours (a plain human figure: how long did the work take), or leave the cell empty and
|
|
fill it in by hand.
|
|
|
|
Standard library only.
|
|
"""
|
|
|
|
import argparse
|
|
import os
|
|
import sqlite3
|
|
import sys
|
|
from datetime import datetime, timezone
|
|
|
|
DEFAULT_STATE_DB = "~/.hermes/state.db"
|
|
|
|
|
|
def expand_children(con, seed_ids):
|
|
"""The given sessions plus every session whose parent is, through any number of levels, one of them."""
|
|
seen = set(seed_ids)
|
|
frontier = list(seed_ids)
|
|
|
|
while frontier:
|
|
placeholders = ",".join("?" for _ in frontier)
|
|
found = con.execute(f"SELECT id FROM sessions WHERE parent_session_id IN ({placeholders})", frontier).fetchall()
|
|
frontier = [row[0] for row in found if row[0] not in seen]
|
|
seen.update(frontier)
|
|
|
|
return sorted(seen)
|
|
|
|
|
|
def totals(con, session_ids):
|
|
"""Steps, output, input, written to the cache, read from the cache: in all and per model; and the ids not found."""
|
|
placeholders = ",".join("?" for _ in session_ids)
|
|
rows = con.execute(
|
|
f"""SELECT id, model, api_call_count, output_tokens, input_tokens, cache_write_tokens, cache_read_tokens
|
|
FROM sessions WHERE id IN ({placeholders})""",
|
|
list(session_ids),
|
|
).fetchall()
|
|
|
|
row = [0, 0, 0, 0, 0]
|
|
per_model = {}
|
|
|
|
for _id, model, *counts in rows:
|
|
add = [count or 0 for count in counts]
|
|
mine = per_model.setdefault(model or "?", [0, 0, 0, 0, 0])
|
|
|
|
for index, value in enumerate(add):
|
|
row[index] += value
|
|
mine[index] += value
|
|
|
|
return row, per_model, set(session_ids) - {row[0] for row in rows}
|
|
|
|
|
|
def number(value):
|
|
return f"{value:,}".replace(",", ".")
|
|
|
|
|
|
def show(name, row):
|
|
steps, out, new, written, read = row
|
|
print(f"{name}: {steps} steps | output {number(out)} | input {number(new)} | cache written {number(written)} | cache read {number(read)} | together {number(out + new + written + read)}")
|
|
|
|
|
|
def lines(per_model, text, day, version, hours):
|
|
"""The rows for the table: one per model, the model with the most steps first, the hours on that row only."""
|
|
result = []
|
|
|
|
for position, model in enumerate(sorted(per_model, key=lambda name: -per_model[name][0])):
|
|
if position > 0:
|
|
cell = "0,00"
|
|
else:
|
|
cell = "" if hours is None else f"{hours:.2f}".replace(".", ",")
|
|
|
|
cells = [day, text, version or "", model] + [number(value) for value in per_model[model]] + [cell]
|
|
result.append("| " + " | ".join(cells) + " |")
|
|
|
|
return result
|
|
|
|
|
|
def main(argv=None):
|
|
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
parser.add_argument("session_ids", nargs="+")
|
|
parser.add_argument("--state-db", default=DEFAULT_STATE_DB)
|
|
parser.add_argument("--include-children", action="store_true")
|
|
parser.add_argument("--row")
|
|
parser.add_argument("--version", default="")
|
|
parser.add_argument("--date", default=datetime.now(timezone.utc).strftime("%Y-%m-%d"))
|
|
parser.add_argument("--hours", type=float, default=None)
|
|
args = parser.parse_args(argv)
|
|
|
|
path = os.path.expanduser(args.state_db)
|
|
|
|
if not os.path.exists(path):
|
|
sys.exit(f"No Hermes state file at {path} (use --state-db).")
|
|
|
|
con = sqlite3.connect(path)
|
|
session_ids = expand_children(con, args.session_ids) if args.include_children else args.session_ids
|
|
|
|
if args.include_children:
|
|
print(f"sessions counted (given + children): {', '.join(session_ids)}", file=sys.stderr)
|
|
|
|
row, per_model, missing = totals(con, session_ids)
|
|
|
|
if missing:
|
|
print(f"WARNING: not found in state.db, not counted: {', '.join(sorted(missing))}", file=sys.stderr)
|
|
|
|
show("sessions", row)
|
|
|
|
if args.row:
|
|
if not per_model:
|
|
per_model = {"?": [0, 0, 0, 0, 0]}
|
|
|
|
if args.hours is None:
|
|
print("NOTE: no --hours given: fill in the Uren cell by hand, do not invent a figure.", file=sys.stderr)
|
|
|
|
print("\n".join(lines(per_model, args.row, args.date, args.version, args.hours)))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|