Logo vun Token Doctor

Token Doctor

Organisatioun
techwolf-ai
token-doctor

Personal diagnosis of where your Claude Code + Cowork spend goes. Reads local transcripts, prints your conversation length distribution, marathon share, cache rebuild costs, and per-project diagnosis (good projects and problem projects) right in the terminal. Then offers a deeper dive that fans out parallel Haiku subagents over your most expensive (and most efficient) sessions and writes a tight Markdown report. Use when the user asks "why is my Claude spend so high", "where am I burning tokens", "diagnose my Claude habits", "audit my Claude usage", or asks for a personal token-cost diagnosis.

Iwwersiicht

Editeurtechwolf-ai
Repositoryai-first-toolkit
Skill-Nummtoken-doctor
Stären
138
Forks
7
Matgeliwwert Fichieren
11
LizenzMIT
Linken
  • Instruktiounen am Markdown-Format

    Eng SKILL.md-Datei, déi de Modell bei Bedarf luet, soudatt nëmmen Token ufalen, wann eng Ufro tatsächlech dozou passt.

  • Funktionéiert mat all LLM

    KI-Skills si reng Markdown, keen ubidderspezifesche Code. Dofir funktionéiert dëse Skill mat GPT, Claude, Gemini, Grok oder engem lokale Modell.

  • 11 matgeliwwert Dateien

    Skripten, Virlagen a Referenzen, déi de Modell beim Schaffe liese kann. D'Dateie kënnen nëmme gelies ginn a ginn ni ausgeféiert.

  • Open Source

    Vum techwolf-ai op GitHub verëffentlecht. Liest de Quelltext, ier Dir de Skill installéiert.

Installatioun

Installéiert de KI-Skill Token Doctor an TypingMind, fir e mat all LLM ze benotzen, oder füügt en an en anere KI-Agent an, deen SKILL.md liest.

1

An TypingMind installéieren

TypingMind installéiert e Skill direkt aus sengem GitHub-Dossier — dobäi gëtt SKILL.md gelies, d'Ressourcedateie gi gebëndelt an d'Resultat gëtt lokal gespäichert.

  1. Maacht d'App op a gitt op Plugins → Skills.
  2. Wielt „Vun GitHub installéieren“.
  3. Pecht d'URL vum Skill-Dossier hei drënner an a bestätegt.
    https://github.com/techwolf-ai/ai-first-toolkit/tree/main/plugins/ai-adoption/skills/token-doctor
  4. Aktivéiert de Skill an all Chat, an deem Dir e benotze wëllt.
Plugins → Skills → Skill afügen → Vu GitHub-URL, pecht dann d'URL vum Dossier an a klickt op Weider.
2

An engem anere KI-Agent installéieren

All KI-Agent, deen d'Format Agent Skills liest, kann dëse Skill benotzen — kopéiert den Dossier an de Skill-Verzeechnes vun deem KI-Agent.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/techwolf-ai/ai-first-toolkit.git /tmp/ai-first-toolkit
mkdir -p .claude/skills
cp -r /tmp/ai-first-toolkit/plugins/ai-adoption/skills/token-doctor .claude/skills/token-doctor
Start Claude Code nom Kopéieren nei, fir datt den neie Skill erkannt gëtt.

An TypingMind benotzen

Aktivéiert Token Doctor an engem Chat vun TypingMind, an de Modell iwwerhëlt de Rescht. Den Numm an d'Beschreiwung stinn am System-Prompt. Soubal eng Ufro dozou passt, luet de Modell déi komplett Instruktioune selwer — Dir musst de Skill ni manuell opruffen, an et fale keng Token un, bis en tatsächlech benotzt gëtt.

De Modell luet Token Doctor automatesch, soubal eng Ufro dozou passt.

Funktionéiert mat all KI-Modell

KI-Skills si reng Markdown-Instruktiounen amplaz vun ubidderspezifeschem Code. Dofir ass Token Doctor net un de Modell gebonnen, fir deen de Skill geschriwwe gouf. Installéiert en eemol an TypingMind a benotzt e mat GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama oder engem lokale Modell, deen Dir selwer bedreift — alles mat Ären eegenen API-Keys.

  • Gëtt nëmme gelueden, wann et néideg ass

    De System-Prompt enthält nëmmen den Numm an d'Beschreiwung. D'Instruktioune gi bei der éischter passender Ufro gelueden, soudatt en onbenotzte Skill näischt kascht.

  • De Modell am lafende Chat wiesselen

    Well de Skill aus Instruktiounen amplaz vu Code besteet, funktionéiert en och no engem Modellwiessel — den nächste Modell liest déi selwecht SKILL.md-Datei.

Skill-Instruktiounen

Dëst ass den Inhalt vu SKILL.md, deen de Modell luet. Liest e virun der Installatioun — e Skill besteet aus Instruktiounen, déi Äre Modell befollegt.

Token Doctor

Platforms: Claude Code / Cowork and Codex. scripts/inventory.py detects the host (via the platform stamp install.sh writes, or AI_FIRST_PLATFORM) and routes: Claude Code (~/.claude/projects) + Cowork transcripts, or Codex rollouts (~/.codex/sessions). Codex token usage comes from Codex's own per-response token_count events; cost uses OpenAI list rates in pricing.py (gpt-5.4 family; unknown models show token counts with no fabricated cost). Antigravity is unsupported: its IDE store is AEAD-encrypted at rest and its CLI store has no parseable turn/token content, so the skill prints a clear "not available" message and exits.

Two-stage diagnostic. Stage 1 is fast and lands directly in the terminal so the user always walks away with their numbers. Stage 2 is opt-in, fans out subagents over hotspots, and writes a tight Markdown report.

Read this whole file before running.

When to run

Trigger phrases: "diagnose my Claude habits", "why am I spending so much", "where are my tokens going", "audit my spend", "token doctor", "what's driving my Claude bill".

Do NOT trigger for:

  • "what tasks do I do with Claude" → that's task-profile.
  • "where did I work on X" → that's session-search.

The line is: token-doctor is about cost shape, not task inventory or recall.

Prerequisites

  • Claude Code transcripts: ~/.claude/projects/*/*.jsonl (CLI and desktop app)
  • Sub-agent transcripts: ~/.claude/projects/*/<sid>/subagents/**/*.jsonl, including workflow agents under subagents/workflows/<wf>/
  • Claude Cowork transcripts (optional): ~/Library/Application Support/Claude/local-agent-mode-sessions/*/*/local_*/audit.jsonl
  • Python 3, stdlib only. No external services.

If neither path exists, stop and say so.

What counts as one session

Sub-agent transcripts are separate files but the same piece of work, so their cost rolls into the parent session rather than appearing as sessions of their own. This matters when you read the report:

  • cost_usd is main conversation plus fan-out. main_cost_usd and subagent_cost_usd split it.
  • Turn counts, the timeline, cache rebuilds and the re-read ratio are main-session figures. They describe how that one conversation's context grew; sub-agents have their own context.
  • So a session can show 100 turns and $641. That is not a contradiction, it is fan-out. Say so rather than letting the reader trip over it.
  • One turn = one assistant message, not one transcript line. Claude Code writes a line per content block (thinking, text, each tool_use) and repeats the same usage object on every one, so counting lines inflates turns and cost by roughly 2-3x. The inventory dedupes by message.id. Turn counts from an older run of this skill are not comparable with these.

Automation excluded by default: sdk-cli background dispatch, paperclip, ditto-routines, scheduled tasks, and the automation slash commands. Desktop-app sessions are interactive work and are counted.


STAGE 1 — Fast diagnosis (always runs, you write the report)

The goal is: the user invokes the skill, sees a clean doctor's report within 10 seconds, knows which projects are healthy and which are bleeding, and can decide whether to go deeper. You write the report directly in your message based on the JSON the scripts produce. The scripts compute, you communicate.

Step 1.1 — Inventory (deterministic)

bash
~/.claude/skills/token-doctor/scripts/inventory.py --since YYYY-MM-DD --out out/sessions.jsonl

Default window: last 90 days. Flags: --since, --until, --all, --include-automation, --no-cowork. Automation runs (sdk-cli background dispatch, paperclip, /loop, /schedule, ditto-routines, scheduled-tasks) excluded by default.

--until YYYY-MM-DD means midnight at the start of that day, so it excludes that day's sessions. To include today, leave --until off.

The scan prints how many sub-agent transcripts it rolled into parent sessions. If it also reports sub-agents with no parent session on disk, that cost is not in the totals; mention it only if it is material.

Step 1.2 — Aggregate (deterministic)

bash
~/.claude/skills/token-doctor/scripts/personal_stats.py --in out/sessions.jsonl --out out/user-stats.json

Prints a single confirmation line. The full data is in out/user-stats.json.

Step 1.3 — Read the JSON and write the doctor's report

Read out/user-stats.json. Then write the report directly in your message as terminal-style ASCII with emojis. The user reads your message; no intermediate file.

Report structure (mandatory sections, in order)
🩺 ┌────────────────────────────────────────────────────────────────────┐
   │            TOKEN DOCTOR · personal diagnosis                       │
   └────────────────────────────────────────────────────────────────────┘

  Patient: <user's first name or "you">
  Window:  <window dates from inventory>
  Spend:   $<total> list-price equivalent · <conv count> conversations

  ── Vital signs ─────────────────────────────────────────────────────────

  🔴/🟡/🟢 Marathon (≥300 turns)    <N> conv  ·  $<X>  ·  <Y>% of spend
  🔴/🟡/🟢 Fan-out (≥5 sub-agents)  <N> conv  ·  $<X>  ·  <Y>% of spend
  🔴/🟡/🟢 Zombie (≥4h wall clock)  <N> conv  ·  $<X>  ·  <Y>% of spend
  🔴/🟡/🟢 Cache rebuilds            <N> events · <Z>M tokens · ~$<X>
  🔴/🟡/🟢 Re-read ratio             <X>×   (healthy ≤15×, org avg 30×)
  📈 Peak context observed       <X>k tokens
  🌳 Sub-agent cost               $<X> of $<total>  (<Y>%) across <N> transcripts

  ── Spend by conversation length ────────────────────────────────────────

       1 to 5        <bar>   <%>   (<N> conv)
       6 to 20       <bar>   <%>   (<N> conv)
       …
       1,000+        <bar>   <%>   (<N> conv)

  ── Model mix ───────────────────────────────────────────────────────────

    <model>        $<X>   <%>   <N> turns    main $<X>/<N>t · sub $<X>/<N>t
    <model>        $<X>   <%>   <N> turns    main $<X>/<N>t · sub $<X>/<N>t
    …

  ── Diagnosis ───────────────────────────────────────────────────────────

  <2-4 sentences synthesizing the vitals into one clear picture. Lead with
  the dominant antipattern in this user's data, then the corollary cost. End
  with one line about the strongest positive signal you see.>

  ── Project chart ───────────────────────────────────────────────────────

  ✅ clean · 🏃 marathon · 🌳 fanout · 🔄 rebuilds · 🧟 zombie · ⚠️ multiple

  <emoji>  $<X>  <truncated cwd>                              <meta line>
  <emoji>  $<X>  <truncated cwd>                              <meta line>
  … up to 10-12 rows from by_cwd_top

  ── Treatment plan ──────────────────────────────────────────────────────

  💚 Keep doing:
     <bullet referencing a clean project from by_cwd_top or by_cwd_clean_deeper,
      OR a positive structural signal like a high short_share if no clean cwd is in top 12>
     <2-3 bullets total>

  🎯 Change first:
     <one concrete action tied to the biggest lever, with cited project>
     <2-3 bullets total, ordered by expected impact>

  ── Want a deeper look? ─────────────────────────────────────────────────

  <one-line question asking if they want the deep dive>
Rules when writing the report
  • Use the emojis above consistently. Box-drawing characters (─ ┌ └ │) are fine and make the report look like a medical printout.
  • Traffic-light dots: 🔴 = bad, 🟡 = watch, 🟢 = healthy. Apply the bands in the rubric below.
  • Per-project emoji must come from by_cwd_top[i].emoji in the JSON. Do not re-classify.
  • Model mix comes from model_mix, already sorted by cost. Show every model down to 1% of spend, then stop. Use readable names (claude-opus-5 → Opus 5, claude-fable-5-1 → Fable 5.1). The main / sub split is the point of the section: a model that is cheap in the main conversation and expensive across sub-agents is the clearest lever in the whole report, because sub-agent model tier is a one-line change in an Agent(...) call. Call that out when you see it.
  • Fan-out uses fanout_conv / fanout_cost / fanout_share (sessions with ≥ 5 sub-agents) and subagent_cost / subagent_share (fan-out's share of total spend). If subagent_files is 0, drop both the fan-out vital and the sub-agent line rather than printing zeroes.
  • Bars for the length distribution: build them with █ characters proportional to the share. Use a fixed width like 36 chars.
  • The diagnosis paragraph is yours to write — it is the doctor's read on the data. Be specific. Don't restate the numbers; conclude from them. Aim for 3-5 sentences max. Examples of good diagnostic sentences:
    • "Your spend is concentrated in a small number of very long sessions: 22 conversations carry 70% of your bill."
    • "Cache rebuilds are minor at $388, but the re-read ratio of 23× tells me your context grows fast inside those long sessions."
    • "Three of your top five projects are evaluation runs from last month. Each is one long session; splitting them would compound."
  • Treatment plan must include both "keep doing" AND "change first" sections. Skipping the positive section is forbidden. Pick from:
    • by_cwd_top entries with emoji == "✅" for clean
    • by_cwd_clean_deeper for clean projects below the top 12
    • short_share if neither is available — frame as "X% of your spend is in short focused sessions, so the habit is there, you just don't use it everywhere"
  • Cite specific projects. Truncate cwds to the last 36-44 chars with a leading … if they're long. Drop the /Users/<name>/ prefix when it makes the line cleaner.
  • No em-dashes. Use commas, semicolons, or periods.
  • No "waste", "burning", "bad habit". Use "cost", "spend", "context", "rebuild".
Traffic-light thresholds
Metric🟢🟡🔴
Marathon share< 20%20-50%≥ 50%
Fan-out share< 20%20-50%≥ 50%
Zombie share< 20%20-50%≥ 50%
Cache rebuild $< $50$50-$200≥ $200
Re-read ratio≤ 15×15-35×≥ 35×
Asking about the deep dive

End with one short line, not a paragraph. Example:

Want me to pull apart your top sessions one by one — what specifically drove each marathon, plus a couple of your most efficient runs to learn from? Takes about a minute, runs ~15 Haiku subagents in parallel.

If they say no, stop. The report is the deliverable.


STAGE 2 — Deep dive (opt-in)

Step 2.1 — Pick hotspots

bash
~/.claude/skills/token-doctor/scripts/pick_hotspots.py --in out/sessions.jsonl --out out/hotspots.json

Selects ~14 sessions:

  • 8 by absolute cost
  • 3 by cache rebuild tokens
  • 3 by raw turn count
  • 3 by read:create ratio at ≥$5 cost
  • 3 positive examples (lowest cost-per-turn at 20-100 turns)

Briefly tell the user the list before fan-out so they can drop sensitive sids. Keep it to one line per session: $X · N turns · short title.

Step 2.2 — Build payloads

bash
~/.claude/skills/token-doctor/scripts/build_payloads.py --sessions out/sessions.jsonl --hotspots out/hotspots.json --outdir out/payloads

Writes one redacted payload per hotspot. Payloads include token shape, tool-call counts, timeline samples, and a 120-char title. They do NOT include user prompt bodies or model output text.

Step 2.3 — Parallel subagent fan-out

For each payload in out/payloads/, dispatch one subagent. Send all calls in one message with multiple tool blocks so they run in parallel.

Agent(
  description="Diagnose one session",
  subagent_type="general-purpose",
  model="haiku",
  run_in_background=true,
  prompt="""
Diagnose the session at out/payloads/<sid>.json.

Read first, in order:
  1. ~/.claude/skills/token-doctor/references/antipattern-taxonomy.md
  2. ~/.claude/skills/token-doctor/references/diagnosis-rubric.md
  3. out/payloads/<sid>.json

Apply the rubric. Emit strictly the JSON schema (see rubric §Output) to out/analyses/<sid>.json. Hard length limits: what_happened max 2 sentences (~25 words), trigger_moment.what max 14 words, would_have_helped max 18 words. Lead with structural facts (turn count, context size, key signal). No restating the schema.

Tone: second-person, neutral, no "waste" / "burning".
"""
)

Wait for all to complete.

Step 2.4 — Synthesize the report (main agent)

Read every out/analyses/*.json. Then:

  1. Group by cwd. For each cwd that has ≥2 analyzed sessions, decide if it shows a dominant pattern.
  2. Find the signature: the one antipattern that recurs most across the user's data, and the one positive habit they have consistently.
  3. Write out/recommendations.md — tight, scannable, no padding. Structure:
markdown
# Token Doctor — your diagnosis

**Signature.** <one sentence: dominant antipattern + dominant strength>

**Bottom-line lever.** <one sentence: the single habit change with the biggest expected impact>

## What you're doing well

- **<positive pattern>** in `<cwd>`. <one sentence with one cited sid>
- **<positive pattern>** in `<cwd>`. <one sentence with one cited sid>

(2-3 bullets. At least one is mandatory; do not skip this section.)

## What's driving your bill

- **<antipattern>** in `<cwd>`. <one sentence. Cite the worst sid and one specific turn or signal>
- ...

(3-5 bullets ordered by estimated savings)

## Per-session diagnoses

| Cost | Turns | Verdict | What happened |
|---:|---:|---|---|
| $XXX | NNN | <label> | <1-2 line what_happened from the analysis> |
| ...

(Only the analyzed sessions. Use the `what_happened` field verbatim from each analysis JSON.)

Also write out/recommendations.json with structured form for re-use:

json
{
  "signature": {
    "primary_antipattern": "marathon | drip-feed | zombie | bloat | grind | drift | fanout | none",
    "primary_strength": "focused | front-loaded | time-bounded | lean | directed | none",
    "one_line": "<one sentence about how this user's spend is shaped>"
  },
  "bottom_line_lever": "<one sentence>",
  "positives": [{"pattern": "...", "cwd": "...", "evidence_sid": "...", "note": "..."}],
  "antipatterns": [{"pattern": "...", "cwd": "...", "evidence_sids": ["..."], "note": "...", "expected_impact": "small|medium|large"}],
  "session_table": [{"sid": "...", "cost": 0, "turns": 0, "verdict": "...", "what_happened": "..."}]
}

Keep the prose terse. The user already has the terminal numbers; the report's job is to point at specific projects and habits, not to recite stats.


Privacy contract

  • Everything runs locally. No transcript text leaves the machine.
  • Subagents receive token counts, tool-call names, turn indices, and a 120-char title. They do not receive user prompt text or model output text.
  • Output files in out/ contain session ids and short titles. They do not contain conversation content.
  • The user can rm -rf out/ to wipe everything.

Tone

  • Descriptive, not punitive. The user is reading their own data.
  • Both antipatterns and positive habits get airtime. Skipping the "what you're doing well" section is forbidden.
  • Specific numbers, specific turn indices, specific sids. Avoid hedging.
  • No em-dashes. No "waste", "burning", "bad habit".
  • Emojis are allowed in the terminal output (the personal_stats.py script uses them). Keep them out of the Markdown report — there it should look like an engineering doc.

Failure modes

  • No transcripts found. Stop with a clear message.
  • Subagent emitted invalid JSON. Skip that sid, log a warning once, continue.
  • All sessions are automation. Tell the user to re-run with --include-automation if they want those analyzed; otherwise note the interactive count.
  • Single-cwd user. Skip the per-cwd grouping in the report; recommendations still work as a flat list.

Matgeliwwert Fichieren

De Modell liest dës Dateie bei Bedarf, wärend de Skill gelueden ass. Si ginn als liesbar Dateie bereetgestallt a ginn ni ausgeféiert.

Heefeg gestallte Froen

Wat mécht de KI-Skill Token Doctor?

Personal diagnosis of where your Claude Code + Cowork spend goes. Reads local transcripts, prints your conversation length distribution, marathon share, cache rebuild costs, and per-project diagnosis (good projects and problem projects) right in the terminal. Then offers a deeper dive that fans out parallel Haiku subagents over your most expensive (and most efficient) sessions and writes a tight Markdown report. Use when the user asks "why is my Claude spend so high", "where am I burning tokens", "diagnose my Claude habits", "audit my Claude usage", or asks for a personal token-cost diagnosis.

Firwat Token Doctor op TypingMind benotzen?

Well Dir en eemol installéiert a mat all Modell benotze kënnt. Token Doctor besteet aus einfachem Markdown amplaz vun ubidderspezifeschem Code. Dee selwechte Skill funktionéiert also mat GPT-5, Claude, Gemini, Grok oder engem lokale Modell – an Dir kënnt de Modell matzen am Chat wiesselen, ouni datt de Skill ophält ze funktionéieren. TypingMind benotzt Är eegen API-Schlësselen, sou datt Dir d'Ubidder direkt bezuelt amplaz vun engem Abonnement pro Benotzerplaz. Är Skills a Chats bleiwen an Ärem eegene Späicher.

Wéi installéieren ech Token Doctor an TypingMind?

Maacht an TypingMind Plugins → Skills → Vu GitHub installéieren op a setzt https://github.com/techwolf-ai/ai-first-toolkit/tree/main/plugins/ai-adoption/skills/token-doctor an. TypingMind liest d'Datei SKILL.md, bündelt déi zougehéiereg Dateien an installéiert dat Ganzt als Skill, deen Dir pro Chat aktivéiere kënnt.

Wéi eng KI-Modeller kënnen Token Doctor benotzen?

All Modell, deen Dir an TypingMind verbënnt. KI-Skills sinn einfach Markdown-Instruktiounen an net ubidderspezifesche Code. Dofir kënne GPT, Claude, Gemini, Grok a lokal Modeller dëse Skill lueden, wann eng Ufro dozou passt.

Wéi vill KI-Modeller kann ech mat Token Doctor benotzen?

Esou vill Dir wëllt. Soulaang e Modell Skills ënnerstëtzt, kënnt Dir Token Doctor domat benotzen – GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama a méi – alles op TypingMind mat Ären eegenen API-Schlësselen.

Ass de KI-Skill Token Doctor gratis?

Jo. De Skill gëtt vum techwolf-ai ënner der Lizenz MIT op GitHub publizéiert. Dir bezuelt nëmmen Ären eegene KI-Ubidder fir d'Token, déi Dir benotzt.

Wat si KI-Skills?

E KI-Skill ass e weiderverwendbaart Pak vun Instruktiounen, dat engem KI-Modell bäibréngt, wéi en eng bestëmmt Aufgab erfëllt. E follegt dem oppenen Agent Skills-Format: eng Datei SKILL.md mat engem Numm an enger Beschreiwung, plus all Scripten, Virlagen oder Referenzdateien, déi de Modell eventuell brauch. De Modell liest d'Instruktiounen eréischt, wann Är Ufro zum Skill passt. En installéierte Skill kascht also näischt, bis e benotzt gëtt.

Wéi ënnerscheede sech KI-Skills vu Plugins oder MCP-Serveren?

E Plugin oder MCP-Server gëtt engem Modell nei Tools, déi en opruffe kann – Code, deen iergendwou leeft an e Resultat zeréckgëtt. E KI-Skill gëtt dem Modell dogéint Wëssen an eng Virgoensweis: wéi en eng Aufgab ugeet, wéi eng Schrëtt en nokënnt a wéi eng gutt Ausgab ausgesäit. Skills bestinn aus einfachem Markdown, brauche kee Server, keen API-Schlëssel a keng Lafzäitëmfeld a funktionéiere mat all Modell.

All weisen

Elo Ären eegene KI-Workspace ariichten

Abonnéiert Iech op eisen Newsletter, fir iwwer nei Funktiounen an zukünfteg Gewënnspiller informéiert ze ginn 👇