diff --git a/chezmoi/dot_claude/scripts/executable_session-token-log.sh b/chezmoi/dot_claude/scripts/executable_session-token-log.sh new file mode 100755 index 0000000..23bd520 --- /dev/null +++ b/chezmoi/dot_claude/scripts/executable_session-token-log.sh @@ -0,0 +1,21 @@ +#!/usr/bin/env bash +# session-token-log.sh — SessionEnd-хук: пишет токен-расход сессии в self-learning лог. +# Получает на stdin JSON хука (transcript_path). Тихий, без падений (хук не должен ломать выход). +set -uo pipefail + +LOG="$HOME/.claude/self-learning/token-spend.log" +mkdir -p "$(dirname "$LOG")" + +IN=$(cat 2>/dev/null || true) +TP=$(printf '%s' "$IN" | python3 -c "import sys,json; +try: print(json.load(sys.stdin).get('transcript_path','')) +except Exception: print('')" 2>/dev/null) + +[ -n "$TP" ] && [ -f "$TP" ] || exit 0 # нет транскрипта — тихо выходим + +{ + echo "── $(date '+%F %T') ──" + "$HOME/.claude/scripts/token-spend.sh" "$TP" 2>/dev/null + echo +} >> "$LOG" 2>/dev/null || true +exit 0 diff --git a/chezmoi/dot_claude/scripts/executable_token-spend.sh b/chezmoi/dot_claude/scripts/executable_token-spend.sh new file mode 100755 index 0000000..ee4c162 --- /dev/null +++ b/chezmoi/dot_claude/scripts/executable_token-spend.sh @@ -0,0 +1,46 @@ +#!/usr/bin/env bash +# token-spend.sh — разбивка токен-расхода сессии из jsonl (для конца сессии / token-аудита самообучения). +# Использование: token-spend.sh [path/to/session.jsonl] +# без аргумента — берёт самый свежий jsonl проекта текущего cwd. +set -uo pipefail + +F="${1:-}" +if [ -z "$F" ]; then + # имя проекта в ~/.claude/projects кодируется через замену '/' на '-' + KEY=$(pwd | sed 's#/#-#g') + DIR="$HOME/.claude/projects/$KEY" + F=$(ls -t "$DIR"/*.jsonl 2>/dev/null | head -1) +fi +[ -n "$F" ] && [ -f "$F" ] || { echo "jsonl не найден ($F). Передай путь явно."; exit 1; } + +python3 - "$F" <<'PY' +import json, sys +f = sys.argv[1] +it = ot = cc = cr = n = 0 +models = set() +for line in open(f): + try: d = json.loads(line) + except Exception: continue + m = d.get("message", {}) + u = m.get("usage") or {} + if not u: continue + n += 1 + it += u.get("input_tokens", 0); ot += u.get("output_tokens", 0) + cc += u.get("cache_creation_input_tokens", 0); cr += u.get("cache_read_input_tokens", 0) + if m.get("model"): models.add(m["model"]) +# Opus-rate (груб): in $15 / out $75 / cache-write $18.75 / cache-read $1.50 за Mtok +cost = it/1e6*15 + ot/1e6*75 + cc/1e6*18.75 + cr/1e6*1.5 +tot = it + ot + cc + cr +print(f"сессия: {f.split('/')[-1]}") +print(f"вызовов с usage: {n} | модели: {', '.join(models) or '—'}") +print(f"input(uncached): {it:>13,}") +print(f"output: {ot:>13,}") +print(f"cache-write: {cc:>13,}") +print(f"cache-read: {cr:>13,}") +print(f"ВСЕГО: {tot:>13,}") +print(f"≈ стоимость: ${cost:,.2f} (груб. Opus-rate)") +# доминанта +parts = {"input": it, "output": ot, "cache-write": cc, "cache-read": cr} +dom = max(parts, key=parts.get) +print(f"доминанта: {dom} ({parts[dom]/tot*100:.0f}%)") +PY diff --git a/chezmoi/dot_claude/settings.json.tmpl b/chezmoi/dot_claude/settings.json.tmpl index 6f91e39..74e6df3 100644 --- a/chezmoi/dot_claude/settings.json.tmpl +++ b/chezmoi/dot_claude/settings.json.tmpl @@ -46,6 +46,19 @@ } ] } + ], + "SessionEnd": [ + { + "hooks": [ + { + "type": "command", + "command": "bash \"{{ .chezmoi.homeDir }}/.claude/scripts/session-token-log.sh\"", + "async": true, + "timeout": 20, + "statusMessage": "Token-spend → self-learning..." + } + ] + } ] }, "enabledPlugins": {