diff --git a/hooks/agent-event-done.sh b/hooks/agent-event-done.sh index 3508135..81d4b89 100755 --- a/hooks/agent-event-done.sh +++ b/hooks/agent-event-done.sh @@ -39,6 +39,7 @@ fi MODEL=$(printf '%s' "$PAYLOAD" | jq -r '.tool_response.model // .tool_input.model // ""' 2>/dev/null | tr '[:upper:]' '[:lower:]') IN_TOK=$(printf '%s' "$PAYLOAD" | jq -r '.tool_response.usage.input_tokens // 0' 2>/dev/null) OUT_TOK=$(printf '%s' "$PAYLOAD" | jq -r '.tool_response.usage.output_tokens // 0' 2>/dev/null) +TOT_TOK=$(printf '%s' "$PAYLOAD" | jq -r '.tool_response.totalTokens // 0' 2>/dev/null) cost_usd=$(awk -v m="$MODEL" -v i="$IN_TOK" -v o="$OUT_TOK" 'BEGIN{ if(index(m,"haiku")>0){p=0.000001;q=0.000005} else if(index(m,"sonnet")>0){p=0.000003;q=0.000015} @@ -52,8 +53,9 @@ jq -cn \ --argjson duration_ms "$(printf '%s' "$PAYLOAD" | jq '.duration_ms // .tool_response.totalDurationMs // null' 2>/dev/null)" \ --argjson tool_use_count "$(printf '%s' "$PAYLOAD" | jq '.tool_response.totalToolUseCount // null' 2>/dev/null)" \ --argjson cost_usd "$cost_usd" \ + --argjson total_tokens "${TOT_TOK:-0}" \ '{ts:$ts,event:"agent_done",id:$id,outcome:$outcome, - duration_ms:$duration_ms,tool_use_count:$tool_use_count,cost_usd:$cost_usd}' \ + duration_ms:$duration_ms,tool_use_count:$tool_use_count,cost_usd:$cost_usd,total_tokens:$total_tokens}' \ >> "$EVENTS_FILE" 2>/dev/null || true # Remove this spawn from active-children ledger (mirror of spawn hook). diff --git a/scripts/keisei-pet-update.sh b/scripts/keisei-pet-update.sh index cc66f8a..d7cb9c3 100644 --- a/scripts/keisei-pet-update.sh +++ b/scripts/keisei-pet-update.sh @@ -19,9 +19,7 @@ set -u STATE_DIR="${HOME}/.claude/pet" STATE="${STATE_DIR}/state" HISTORY="${STATE_DIR}/history.log" -AGENTS_DIR="${STATE_DIR}/agents" -TOKENS_FILE="${STATE_DIR}/agent_tokens" -mkdir -p "$STATE_DIR" "$AGENTS_DIR" +mkdir -p "$STATE_DIR" # Slurp stdin once (hook JSON). Non-blocking; never hang. INPUT="" @@ -30,29 +28,7 @@ if [ ! -t 0 ]; then INPUT="$(cat 2>/dev/null || true)"; fi event="${1:-}" now=$(date +%s) -# ── emoji maps ────────────────────────────────────────────────────────────── -_agent_emoji() { - case "$1" in - *researcher*) echo "🔬" ;; - *architect*) echo "🏗️" ;; - *critic*) echo "🔪" ;; - *security*) echo "🛡️" ;; - *validator*) echo "✅" ;; - *cost*) echo "💰" ;; - *modal*) echo "☁️" ;; - *fal*ai*|*fal_ai*) echo "🎨" ;; - *ml-implementer*|*ml_implementer*) echo "🧠" ;; - *ml-researcher*|*ml_researcher*) echo "📚" ;; - *infra*) echo "🔧" ;; - *implementer*) echo "⚙️" ;; - *patent*) echo "📜" ;; - Explore|*explore*) echo "🔭" ;; - Plan|*plan*) echo "📐" ;; - *general*) echo "🤖" ;; - *) echo "🤖" ;; - esac -} - +# ── language emoji map (agent emojis live in the renderer keisei-pet.sh) ───── _lang_emoji() { case "$1" in rs) echo "🦀" ;; @@ -88,29 +64,10 @@ if [ "${day:-}" != "$today" ]; then rust_today=0; patents_today=0; violations=0; # ── agent / plan / language events (do not change mood face) ───────────────── case "$event" in - agent_start) - sub="$(printf '%s' "$INPUT" | jq -r '.tool_input.subagent_type // .tool_input.description // "agent"' 2>/dev/null)" - [ -z "$sub" ] && sub="agent" - em="$(_agent_emoji "$sub")" - short="$(printf '%s' "$sub" | tr '[:upper:]' '[:lower:]' | sed -E 's/[^a-z0-9].*$//' | cut -c1-12)" - [ -z "$short" ] && short="agent" - id="${now}-$$-${RANDOM}" - printf '%s|%s|%s\n' "$em" "$short" "$now" > "$AGENTS_DIR/$id" 2>/dev/null || true - exit 0 - ;; - agent_done) - # extract tokens from tool_response if present (Agent results carry usage) - tok="$(printf '%s' "$INPUT" | grep -oE 'total_tokens["[:space:]]*[:=]?[[:space:]]*[0-9]+' | grep -oE '[0-9]+' | head -1)" - if [ -n "${tok:-}" ]; then - prev=0; [ -f "$TOKENS_FILE" ] && prev="$(cat "$TOKENS_FILE" 2>/dev/null || echo 0)" - echo $(( prev + tok )) > "$TOKENS_FILE" 2>/dev/null || true - fi - # remove the oldest running-agent file (FIFO approximation — hooks give no - # stable per-agent id to match start↔done exactly). - oldest="$(ls -1tr "$AGENTS_DIR" 2>/dev/null | head -1)" - [ -n "$oldest" ] && rm -f "$AGENTS_DIR/$oldest" 2>/dev/null || true - exit 0 - ;; + # NOTE: running-agent tracking + token/cost accounting are NOT done here — + # the kit already does it (hooks/task-timer.sh → time-metrics/.task-*.start, + # hooks/agent-event-done.sh → agent-events.jsonl). keisei-pet.sh READS those + # (SSoT). This updater only owns mood / language / plan / counters. plan) plan="📋"; mood="proud"; message="план готов" ;; diff --git a/scripts/keisei-pet.sh b/scripts/keisei-pet.sh index ce8f501..c8b78c9 100644 --- a/scripts/keisei-pet.sh +++ b/scripts/keisei-pet.sh @@ -1,89 +1,98 @@ #!/usr/bin/env bash # KeiSei tamagotchi — statusline renderer. Outputs ONE line. -# Shows: running sub-agents (emoji·name·elapsed) + agent token spend + -# plan state + mood face + message + counters + current language + project. -# State written by keisei-pet-update.sh under ~/.claude/pet/. +# SSoT: reads the kit's OWN tracking, does not maintain a parallel one. +# - running sub-agents ← ~/.claude/memory/time-metrics/.task-.start +# (written by hooks/task-timer.sh: {id,desc,type,start_epoch}) +# - agent token / cost ← ~/.claude/memory/agent-events.jsonl +# (written by hooks/agent-event-done.sh: {tokens,cost_usd,...}) +# - mood / lang / plan ← ~/.claude/pet/state (keisei-pet-update.sh) set -u - -# Discard any stdin (Claude Code pipes session JSON to statusLine). if [ ! -t 0 ]; then cat >/dev/null 2>&1 || true; fi -STATE_DIR="${HOME}/.claude/pet" -STATE="${STATE_DIR}/state" -AGENTS_DIR="${STATE_DIR}/agents" -TOKENS_FILE="${STATE_DIR}/agent_tokens" +STATE="${HOME}/.claude/pet/state" +TM_DIR="${HOME}/.claude/memory/time-metrics" +EVENTS="${HOME}/.claude/memory/agent-events.jsonl" mood="neutral"; message=""; since=$(date +%s) rust_today=0; patents_today=0; violations=0; lang=""; plan="" # shellcheck source=/dev/null [ -f "$STATE" ] && source "$STATE" 2>/dev/null || true - now=$(date +%s) - dim=$'\033[2m'; reset=$'\033[0m' -# ── elapsed pretty-printer (s / m / h) ────────────────────────────────────── +_agent_emoji() { + case "$1" in + *researcher*) echo "🔬";; *architect*) echo "🏗️";; *critic*) echo "🔪";; + *security*) echo "🛡️";; *validator*) echo "✅";; *cost*) echo "💰";; + *modal*) echo "☁️";; *fal*) echo "🎨";; *ml-implementer*|*ml_implementer*) echo "🧠";; + *ml-researcher*|*ml_researcher*) echo "📚";; *infra*) echo "🔧";; *implementer*) echo "⚙️";; + *patent*) echo "📜";; Explore|*explore*) echo "🔭";; Plan|*plan*) echo "📐";; + *) echo "🤖";; + esac +} _elapsed() { local s=$1 - if [ "$s" -lt 60 ] ; then printf '%ds' "$s" - elif [ "$s" -lt 3600 ] ; then printf '%dm' $(( s / 60 )) - else printf '%dh%dm' $(( s / 3600 )) $(( (s % 3600) / 60 )) - fi + if [ "$s" -lt 60 ]; then printf '%ds' "$s" + elif [ "$s" -lt 3600 ]; then printf '%dm' $(( s / 60 )) + else printf '%dh%dm' $(( s / 3600 )) $(( (s % 3600) / 60 )); fi } -# ── running sub-agents (self-clean stale > 1h) ────────────────────────────── -agents="" -if [ -d "$AGENTS_DIR" ]; then - for f in "$AGENTS_DIR"/*; do +# ── running sub-agents (from task-timer's .task-*.start) ───────────────────── +agents=""; n_agents=0 +if [ -d "$TM_DIR" ]; then + for f in "$TM_DIR"/.task-*.start; do [ -f "$f" ] || continue - IFS='|' read -r em name start < "$f" - [ -z "${start:-}" ] && { rm -f "$f" 2>/dev/null; continue; } - age=$(( now - start )) - if [ "$age" -gt 3600 ]; then rm -f "$f" 2>/dev/null; continue; fi - agents+=" ${em}${name}·$(_elapsed "$age")" + typ="$(jq -r '.type // "agent"' "$f" 2>/dev/null)" + st="$(jq -r '.start_epoch // empty' "$f" 2>/dev/null)" + [ -z "$st" ] && continue + age=$(( now - st )) + [ "$age" -gt 7200 ] && continue # ignore stale (kit removes on done) + short="$(printf '%s' "$typ" | tr '[:upper:]' '[:lower:]' | sed -E 's/[^a-z0-9].*$//' | cut -c1-12)" + agents+=" $(_agent_emoji "$typ")${short}·$(_elapsed "$age")" + n_agents=$((n_agents+1)) done fi -# ── agent token spend this session ────────────────────────────────────────── -toks="" -if [ -f "$TOKENS_FILE" ]; then - t=$(cat "$TOKENS_FILE" 2>/dev/null || echo 0) - if [ "${t:-0}" -gt 0 ] 2>/dev/null; then - if [ "$t" -ge 1000000 ]; then toks=" 🪙$(( t / 1000000 ))M" - elif [ "$t" -ge 1000 ] ; then toks=" 🪙$(( t / 1000 ))k" - else toks=" 🪙${t}" - fi +# ── agent token / cost spend today (from agent-events.jsonl) ───────────────── +spend="" +if [ -f "$EVENTS" ]; then + today="$(date -u +%Y-%m-%d)" + read -r tot_tok tot_cost < <(awk -v d="$today" ' + index($0,d)>0 { + t=0; c=0 + if (match($0,/total_tokens[^0-9]*[0-9]+/)) { s=substr($0,RSTART,RLENGTH); gsub(/[^0-9]/,"",s); t=s } + if (match($0,/"cost_usd"[: ]*[0-9.]+/)) { s=substr($0,RSTART,RLENGTH); gsub(/[^0-9.]/,"",s); c=s } + T+=t; C+=c + } END { printf "%d %.4f", T+0, C+0 }' "$EVENTS" 2>/dev/null) + if [ "${tot_cost:-0}" != "0.0000" ] && [ -n "${tot_cost:-}" ]; then + spend=" 💰\$$(printf '%.2f' "$tot_cost" 2>/dev/null)" + elif [ "${tot_tok:-0}" -gt 0 ] 2>/dev/null; then + if [ "$tot_tok" -ge 1000 ]; then spend=" 🪙$(( tot_tok / 1000 ))k"; else spend=" 🪙${tot_tok}"; fi fi fi -# ── mood face + color ─────────────────────────────────────────────────────── +# ── mood face ─────────────────────────────────────────────────────────────── idle=$(( now - since )) -if [ "$idle" -gt 300 ] && [ "$mood" != "angry" ] && [ "$mood" != "alert" ] && [ -z "${agents// }" ]; then +if [ "$idle" -gt 300 ] && [ "$mood" != "angry" ] && [ "$mood" != "alert" ] && [ "$n_agents" -eq 0 ]; then mood="sleep"; message="zzz" fi case "$mood" in - happy) face="(ᵔᴥᵔ)"; color=$'\033[32m' ;; - proud) face="(•̀ᴗ•́)و"; color=$'\033[1;32m';; - thinking) face="(⊙.⊙)"; color=$'\033[36m' ;; - alert) face="(ʘᴗʘ)"; color=$'\033[33m' ;; - angry) face="(ò_ó)"; color=$'\033[31m' ;; - sad) face="(╥﹏╥)"; color=$'\033[34m' ;; - sleep) face="(-.-)"; color=$'\033[2;37m';; - *) face="(•ᴗ•)"; color=$'\033[37m' ;; + happy) face="(ᵔᴥᵔ)"; color=$'\033[32m';; proud) face="(•̀ᴗ•́)و"; color=$'\033[1;32m';; + thinking) face="(⊙.⊙)"; color=$'\033[36m';; alert) face="(ʘᴗʘ)"; color=$'\033[33m';; + angry) face="(ò_ó)"; color=$'\033[31m';; sad) face="(╥﹏╥)"; color=$'\033[34m';; + sleep) face="(-.-)"; color=$'\033[2;37m';; *) face="(•ᴗ•)"; color=$'\033[37m';; esac -# ── counters ──────────────────────────────────────────────────────────────── stats="" [ "${rust_today:-0}" -gt 0 ] 2>/dev/null && stats+=" 🦀${rust_today}" [ "${patents_today:-0}" -gt 0 ] 2>/dev/null && stats+=" 📜${patents_today}" [ "${violations:-0}" -gt 0 ] 2>/dev/null && stats+=" ⚠${violations}" - proj="${PWD##*/}"; [ -z "$proj" ] && proj="~" -# ── render ONE line: [agents][tokens] [plan] face msg stats [lang] 📁proj ──── out="" -[ -n "${agents// }" ] && out+="${agents# }${toks} " +if [ -n "${agents// }" ]; then out+="${agents# }${spend} " +elif [ -n "$spend" ]; then out+="${spend# } "; fi [ -n "$plan" ] && out+="${plan} " out+="${color}${face}${reset}" [ -n "$message" ] && out+=" ${dim}${message}${reset}" diff --git a/settings-snippet.json b/settings-snippet.json index 715fe22..dd2b838 100644 --- a/settings-snippet.json +++ b/settings-snippet.json @@ -65,7 +65,7 @@ }, { "type": "command", - "command": "~/.claude/scripts/keisei-pet-update.sh agent_done" + "command": "~/.claude/hooks/agent-event-done.sh" } ] }, @@ -205,7 +205,7 @@ }, { "type": "command", - "command": "~/.claude/scripts/keisei-pet-update.sh agent_start" + "command": "~/.claude/hooks/agent-event-spawn.sh" } ] }