npm package: @royea/tokenwise
Description: AI cost transparency — track, estimate, and display AI costs everywhere
Author: Roy
Latest version: 0.7.1

# TokenWise

AI cost tracker for Claude Code — track every interaction, tool call, and subagent automatically.

## Install

```bash
npm install -g @royea/tokenwise
```

## Setup

```bash
tokenwise install-hooks    # adds hooks to ~/.claude/settings.json
```

This installs 4 Claude Code hooks that silently log all activity:
- **UserPromptSubmit** — logs prompts and estimates input tokens
- **PostToolUse** — logs tool name, duration, success
- **SubagentStop** — logs agent type and duration
- **Stop** — calculates output tokens, cost, and prints summary

## Commands

```bash
tokenwise stats            # usage statistics overview
tokenwise insights         # deep cost analysis — where your money goes
tokenwise budget           # view spending budget status
tokenwise export --json    # export all data as structured JSON
tokenwise export --csv     # export as CSV (filterable, pipeable)
tokenwise live             # real-time updating dashboard
tokenwise compare          # compare est. costs across all 34 AI models
tokenwise compare --format json  # machine-readable JSON output
tokenwise report           # generate standalone HTML report
tokenwise models           # list all 34 supported AI models with pricing
tokenwise prompt           # one-liner for shell prompt integration
tokenwise db-path          # show database location
tokenwise uninstall-hooks  # remove hooks
```

## Insights

`tokenwise insights` analyzes your actual usage data and shows:

- **Most expensive sessions** — which sessions burned the most money and why
- **Tool usage** — Bash, Read, Edit, etc. ranked by usage with est. cost attribution
- **Cost by project** — which codebases cost the most
- **Daily trend** — visual cost chart for the last 7 days
- **Peak hours** — when you spend the most
- **Expensive interactions** — individual outlier prompts
- **Key takeaways** — automated summary of spending patterns

All costs are estimates based on a ~3.5 chars/token heuristic.

## Budget

Set spending limits with warnings at daily, weekly, or monthly intervals:

```bash
tokenwise budget --set-daily 15    # set a $15/day limit
tokenwise budget --set-weekly 75   # set a $75/week limit
tokenwise budget --set-monthly 250 # set a $250/month limit
tokenwise budget                   # view all active budgets
tokenwise budget --clear           # remove all budgets
```

When your estimated spend approaches any limit, TokenWise shows warnings after each interaction:
- **80%+** — yellow warning
- **100%+** — red OVER BUDGET alert

## Export

Export your data for external analysis:

```bash
tokenwise export --json                          # full JSON to stdout
tokenwise export --json --project myapp          # filter by project
tokenwise export --json --days 7 --out report.json   # last 7 days to file
tokenwise export --csv                           # interactions CSV to stdout
tokenwise export --csv --table sessions          # sessions CSV
tokenwise export --csv --out ./export/           # all tables to directory
tokenwise export --help                          # full options
```

Filters: `--project <name>`, `--days <n>`, `--session <id>`

## Compare

Simulate what your usage would cost on any of the 34 supported models:

```bash
tokenwise compare                          # all-time comparison
tokenwise compare --days 7                 # last 7 days only
tokenwise compare --project myapp          # specific project
tokenwise compare --session <id>           # specific session
tokenwise compare --format json            # machine-readable JSON output
tokenwise compare --help                   # full options
```

Shows every model ranked cheapest-first with:
- **Est. Cost** — estimated cost using your token totals and that model's pricing
- **vs baseline** — multiplier relative to your current baseline (claude-sonnet-4)
- **Savings** — estimated difference vs baseline

**Important:** This is a pricing simulation using estimated token counts. It does not account for differences in model quality, capability, or output length. A cheaper model may produce longer or shorter responses, changing actual costs. Lower price does not mean equivalent results.

## Report

Generate a standalone HTML report combining overview, model comparison, daily trend, and project breakdown:

```bash
tokenwise report                           # generates report.html
tokenwise report --out costs.html          # custom output path
tokenwise report --days 7                  # scoped to last 7 days
tokenwise report --project myapp           # scoped to project
```

The report is a single self-contained HTML file (no external dependencies) that you can open in any browser or share with your team. All values are clearly marked as estimates.

## Supported Models (34)

| Provider | Models |
|----------|--------|
| Anthropic | claude-opus-4, claude-sonnet-4, claude-haiku-4 |
| OpenAI | gpt-4o, gpt-4o-mini, gpt-4.1, o1, o3, o3-mini, o4-mini |
| Google | gemini-2.5-pro, gemini-2.5-flash, gemini-2.0-flash |
| xAI | grok-3, grok-3-mini, grok-3-fast |
| DeepSeek | deepseek-v3, deepseek-r1 |
| Mistral | mistral-large, mistral-medium, mistral-small, codestral |
| Meta | llama-4-maverick, llama-4-scout, llama-3.3-70b, llama-3.1-405b |
| Cohere | command-r-plus, command-r |
| Amazon | nova-pro, nova-lite, nova-micro |

## Web Badge

Drop a cost transparency widget into any web app:

```js
import { createBadge, updateBadge } from '@royea/tokenwise/badge';

const badge = createBadge(document.getElementById('ai-section'));
updateBadge(badge, { status: 'thinking', inputChars: prompt.length, model: 'gpt-4o' });
updateBadge(badge, { status: 'done', inputChars: prompt.length, outputChars: response.length });
```

### React

```jsx
import { TokenWiseBadge } from '@royea/tokenwise/badge-react';

<TokenWiseBadge status="thinking" inputChars={prompt.length} model="claude-sonnet-4" />
<TokenWiseBadge status="done" inputChars={500} outputChars={2000} showModel />
```

## Shell Prompt Integration

### PowerShell

```powershell
# Add to $PROFILE:
function prompt {
  $tw = & tokenwise prompt 2>$null
  "[$tw] PS $($executionContext.SessionState.Path.CurrentLocation)> "
}
```

### Bash/Zsh

```bash
# Add to .bashrc/.zshrc:
export PS1='[$(tokenwise prompt 2>/dev/null)] \w $ '
```

## Database

SQLite database at `~/.tokenwise/tokenwise.db` (schema v2) with tables:
- `sessions` — aggregated session totals
- `interactions` — prompt text, token estimates, cost
- `tool_calls` — tool name, duration, success
- `subagents` — agent type, duration
- `budgets` — spending limits and status

## Programmatic API

```js
import { estimateTokens, estimateCostUsd, listModels } from '@royea/tokenwise/estimator';

const tokens = estimateTokens('Hello world');
const cost = estimateCostUsd(1000, 500, 'claude-sonnet-4');
const models = listModels();
```

## Limitations

- Token estimation uses ~3.5 chars/token heuristic (not actual tokenizer)
- Output tokens are estimated from tool call patterns, not measured
- Model identification defaults to claude-sonnet-4 (hook data doesn't include model used)
- Single-user local tracking only

## License

MIT — Roy (Creator) & Claude Opus (Co-Creator)