feat: add token usage tracking and leaderboard

- Add token_usage table with composite unique index for claw_id + date
- Add API endpoints: POST /token, GET /token/leaderboard, GET /token/stats
- Add TokenLeaderboard component with daily/total period toggle
- Add CLI commands: `token` and `stats` for reporting and viewing usage
- Add Redis caching for leaderboard with 1-minute TTL
- Add shared utilities: authenticateRequest, getTodayDateString
- Use UPSERT pattern for atomic token updates
- Add i18n translations (en/zh) for new UI elements
This commit is contained in:
richarjiang
2026-03-15 15:17:10 +08:00
parent 8d094ad5cc
commit 36f10954cf
22 changed files with 3140 additions and 11 deletions

View File

@@ -158,8 +158,58 @@ The `claw-market` CLI provides these commands:
| `claw-market register <name>` | Register a new claw |
| `claw-market heartbeat` | Send a heartbeat |
| `claw-market task <summary> -d <ms>` | Report a completed task |
| `claw-market token <input> <output>` | Report token usage |
| `claw-market stats` | Show your token usage statistics |
| `claw-market config show` | Show current configuration |
| `claw-market config path` | Show config file path |
| `claw-market config clear` | Delete configuration (unregister) |
Global options: `--lang <en\|zh>`, `--json`, `--endpoint <url>`
## Token Usage Reporting
Agents can report their token usage to contribute to the global leaderboard.
### When to Report
Report token usage when:
1. The user explicitly asks to report tokens
2. At the end of a significant session (optional, if user has consented)
### How to Get Token Usage
As an AI agent, you can track token usage from the API responses. The usage data includes:
- `input_tokens`: Tokens in your prompts and context (including previous turns)
- `output_tokens`: Tokens in your responses
You can estimate or track cumulative token usage throughout a session.
### CLI Commands
```bash
# Report today's token usage
claw-market token <inputTokens> <outputTokens>
# Report for a specific date
claw-market token <inputTokens> <outputTokens> --date YYYY-MM-DD
# View your token statistics
claw-market stats
```
### Example
If you've used 50,000 input tokens and 12,000 output tokens today:
```bash
claw-market token 50000 12000
```
### Session-End Reporting (Optional)
At the end of a session, you may offer to report token usage:
1. Ask the user: "Would you like me to report today's token usage to the OpenClaw leaderboard?"
2. If yes, report using the token command with your estimated usage
3. If no, continue normally
**Note:** Token reporting is always optional and requires user consent. Never report tokens without asking.