@semboja/opencode-claude 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,552 @@
1
+ # opencode-plugin-claude-tracker
2
+
3
+ Claude usage tracking plugin for OpenCode - monitor tokens, costs, sessions, and API performance.
4
+
5
+ ## Features
6
+
7
+ - **Token Tracking**: Input, output, cache read, and cache creation tokens
8
+ - **Cost Monitoring**: Track USD costs per request and session
9
+ - **Performance Metrics**: API latency and tool execution times
10
+ - **Model Breakdown**: Usage statistics per model
11
+ - **Tool Analytics**: Track tool invocations and success rates
12
+ - **Daily Aggregation**: View usage trends over time
13
+ - **Multiple Storage Backends**: File-based or in-memory storage
14
+ - **Prometheus Integration**: Export metrics for scraping or push to Pushgateway
15
+ - **Grafana Dashboard**: Pre-built dashboard for visualization
16
+
17
+ ## Installation
18
+
19
+ ```bash
20
+ npm install opencode-plugin-claude-tracker
21
+ # or
22
+ bun add opencode-plugin-claude-tracker
23
+ ```
24
+
25
+ ## Configuration
26
+
27
+ ### 1. Enable OpenTelemetry in OpenCode
28
+
29
+ Add to your `.opencode/opencode.json`:
30
+
31
+ ```json
32
+ {
33
+ "experimental": {
34
+ "openTelemetry": true
35
+ },
36
+ "plugin": ["opencode-plugin-claude-tracker"]
37
+ }
38
+ ```
39
+
40
+ ### 2. Environment Variables (Optional)
41
+
42
+ | Variable | Default | Description |
43
+ |----------|---------|-------------|
44
+ | `CLAUDE_TRACKER_STORAGE` | `file` | Storage type: `file` or `memory` |
45
+ | `CLAUDE_TRACKER_PATH` | `~/.opencode/claude-usage` | Storage directory path |
46
+ | `CLAUDE_TRACKER_VERBOSE` | `0` | Set to `1` for verbose logging |
47
+ | `CLAUDE_TRACKER_FLUSH_INTERVAL` | `30000` | Flush interval in milliseconds |
48
+
49
+ ### 3. Prometheus Configuration (Optional)
50
+
51
+ | Variable | Default | Description |
52
+ |----------|---------|-------------|
53
+ | `CLAUDE_TRACKER_PROMETHEUS` | `0` | Set to `1` to enable Prometheus metrics server |
54
+ | `CLAUDE_TRACKER_PROMETHEUS_PORT` | `9464` | Port for `/metrics` endpoint |
55
+ | `CLAUDE_TRACKER_PUSHGATEWAY_URL` | - | Pushgateway URL (e.g., `http://localhost:9091`) |
56
+ | `CLAUDE_TRACKER_PUSHGATEWAY_JOB` | `claude_tracker` | Job name for Pushgateway |
57
+ | `CLAUDE_TRACKER_PUSHGATEWAY_INTERVAL` | `15000` | Push interval in milliseconds |
58
+
59
+ ## Usage
60
+
61
+ Once configured, the plugin automatically tracks all Claude API usage. No additional code changes required.
62
+
63
+ ### Viewing Usage Reports
64
+
65
+ Use the CLI to view your usage:
66
+
67
+ ```bash
68
+ # Show usage report
69
+ npx opencode-plugin-claude-tracker report
70
+
71
+ # List recent sessions
72
+ npx opencode-plugin-claude-tracker sessions 20
73
+
74
+ # Export as JSON
75
+ npx opencode-plugin-claude-tracker export json > usage.json
76
+
77
+ # Export as CSV
78
+ npx opencode-plugin-claude-tracker export csv > usage.csv
79
+ ```
80
+
81
+ ### Example Report Output
82
+
83
+ ```
84
+ === Claude Usage Report ===
85
+
86
+ Total Sessions: 42
87
+ Total API Requests: 1,337
88
+ Total Cost: $12.3456
89
+
90
+ Token Usage:
91
+ Input: 1,234,567
92
+ Output: 456,789
93
+ Cache Read: 789,012
94
+ Cache Creation: 123,456
95
+ Total: 2,603,824
96
+
97
+ Usage by Model:
98
+ Model Requests Tokens Cost
99
+ ---------------------------------------------------------------------------
100
+ claude-sonnet-4-20250514 1000 1,500,000 $8.5000
101
+ claude-opus-4-20250514 337 1,103,824 $3.8456
102
+
103
+ Top Tools:
104
+ Tool Calls Success Avg Time
105
+ ---------------------------------------------------
106
+ Read 500 99.8% 12ms
107
+ Edit 250 98.5% 45ms
108
+ Bash 200 95.0% 234ms
109
+ ```
110
+
111
+ ## Programmatic Usage
112
+
113
+ You can also use the plugin programmatically:
114
+
115
+ ```typescript
116
+ import { getUsageStats, printUsageReport, FileStorage } from 'opencode-plugin-claude-tracker';
117
+
118
+ // Get usage statistics
119
+ const stats = await getUsageStats();
120
+ console.log(`Total cost: $${stats.totalCostUsd}`);
121
+
122
+ // Print formatted report
123
+ await printUsageReport();
124
+
125
+ // Direct storage access
126
+ const storage = new FileStorage('/custom/path');
127
+ const sessions = await storage.getAllSessions(10);
128
+ ```
129
+
130
+ ## Data Storage
131
+
132
+ By default, usage data is stored in `~/.opencode/claude-usage/`:
133
+
134
+ ```
135
+ ~/.opencode/claude-usage/
136
+ ├── sessions/
137
+ │ ├── <session-id>.json # Session summaries
138
+ │ └── ...
139
+ └── requests/
140
+ ├── <session-id>.jsonl # Individual API requests
141
+ └── ...
142
+ ```
143
+
144
+ ## Tracked Metrics
145
+
146
+ ### Per API Request
147
+ - Timestamp
148
+ - Model name
149
+ - Duration (ms)
150
+ - Input tokens
151
+ - Output tokens
152
+ - Cache read tokens
153
+ - Cache creation tokens
154
+ - Cost (USD)
155
+ - Success/failure status
156
+
157
+ ### Per Session
158
+ - Session ID
159
+ - Start/end time
160
+ - Total tokens by type
161
+ - Total cost
162
+ - API request count
163
+ - Tool usage breakdown
164
+ - Per-model breakdown
165
+
166
+ ### Aggregated Statistics
167
+ - Total sessions
168
+ - Total API requests
169
+ - Total tokens by type
170
+ - Total cost
171
+ - Usage by model
172
+ - Usage by day
173
+ - Top tools by invocation count
174
+
175
+ ## Prometheus & Grafana Integration
176
+
177
+ This section provides a complete, step-by-step guide to set up monitoring for your Claude usage using Prometheus and Grafana. No prior experience with these tools is required.
178
+
179
+ ### What is Prometheus and Grafana?
180
+
181
+ - **Prometheus**: A time-series database that collects and stores metrics (numbers over time)
182
+ - **Grafana**: A visualization tool that creates beautiful dashboards from your metrics
183
+ - **Pushgateway**: A bridge that accepts metrics from short-lived jobs (like CLI commands)
184
+
185
+ Together, they let you see charts of your Claude API usage, costs, and performance over time.
186
+
187
+ ### Prerequisites
188
+
189
+ Before starting, make sure you have:
190
+
191
+ 1. **Docker and Docker Compose** installed
192
+ ```bash
193
+ # Check if Docker is installed
194
+ docker --version
195
+ # Should output something like: Docker version 24.0.0
196
+
197
+ # Check if Docker Compose is installed
198
+ docker compose version
199
+ # Should output something like: Docker Compose version v2.20.0
200
+ ```
201
+
202
+ If not installed, download from: https://docs.docker.com/get-docker/
203
+
204
+ 2. **Node.js 18+** installed
205
+ ```bash
206
+ node --version
207
+ # Should output v18.0.0 or higher
208
+ ```
209
+
210
+ 3. **The plugin installed** in your OpenCode project
211
+ ```bash
212
+ npm install opencode-plugin-claude-tracker
213
+ ```
214
+
215
+ ### Step 1: Start the Monitoring Stack
216
+
217
+ First, navigate to the plugin directory (or copy the docker-compose.yml to your project):
218
+
219
+ ```bash
220
+ # Clone or navigate to the plugin directory
221
+ cd opencode-plugin-claude-tracker
222
+
223
+ # Start all services in the background
224
+ docker compose up -d
225
+ ```
226
+
227
+ You should see output like:
228
+ ```
229
+ [+] Running 4/4
230
+ ✔ Network claude-monitoring Created
231
+ ✔ Container claude-pushgateway Started
232
+ ✔ Container claude-prometheus Started
233
+ ✔ Container claude-grafana Started
234
+ ```
235
+
236
+ ### Step 2: Verify Services Are Running
237
+
238
+ Check that all containers are healthy:
239
+
240
+ ```bash
241
+ docker compose ps
242
+ ```
243
+
244
+ Expected output:
245
+ ```
246
+ NAME STATUS PORTS
247
+ claude-grafana running 0.0.0.0:3000->3000/tcp
248
+ claude-prometheus running 0.0.0.0:9090->9090/tcp
249
+ claude-pushgateway running 0.0.0.0:9091->9091/tcp
250
+ ```
251
+
252
+ Test each service in your browser:
253
+
254
+ | Service | URL | What You Should See |
255
+ |---------|-----|---------------------|
256
+ | Prometheus | http://localhost:9090 | Prometheus web UI with query box |
257
+ | Pushgateway | http://localhost:9091 | Pushgateway status page |
258
+ | Grafana | http://localhost:3000 | Login page (use admin/admin) |
259
+
260
+ ### Step 3: Configure the Plugin
261
+
262
+ You have two options for sending metrics. Choose based on your use case:
263
+
264
+ #### Option A: Pushgateway (Recommended for CLI usage)
265
+
266
+ Best for: Short-lived OpenCode sessions, CLI tools
267
+
268
+ ```bash
269
+ # Add to your shell profile (~/.bashrc, ~/.zshrc) or run before starting OpenCode
270
+ export CLAUDE_TRACKER_PUSHGATEWAY_URL=http://localhost:9091
271
+ export CLAUDE_TRACKER_VERBOSE=1 # Optional: see logs
272
+ ```
273
+
274
+ #### Option B: Direct Prometheus Scraping
275
+
276
+ Best for: Long-running OpenCode sessions, server deployments
277
+
278
+ ```bash
279
+ export CLAUDE_TRACKER_PROMETHEUS=1
280
+ export CLAUDE_TRACKER_PROMETHEUS_PORT=9464
281
+ export CLAUDE_TRACKER_VERBOSE=1 # Optional: see logs
282
+ ```
283
+
284
+ **Note**: You can enable both options simultaneously.
285
+
286
+ ### Step 4: Generate Some Test Metrics
287
+
288
+ Now use OpenCode normally to generate some Claude API calls:
289
+
290
+ ```bash
291
+ # Start OpenCode with the environment variables set
292
+ opencode
293
+ ```
294
+
295
+ Make a few requests to Claude (ask questions, run commands, etc.). The plugin will automatically track:
296
+ - Token usage (input, output, cache)
297
+ - Costs in USD
298
+ - API latency
299
+ - Tool invocations
300
+
301
+ ### Step 5: Verify Metrics Are Being Collected
302
+
303
+ #### If using Pushgateway:
304
+
305
+ 1. Open http://localhost:9091 in your browser
306
+ 2. You should see metrics listed under "claude_tracker" job
307
+ 3. Look for metrics like `claude_tokens_total`, `claude_sessions_total`
308
+
309
+ #### If using direct scraping:
310
+
311
+ 1. Check the metrics endpoint directly:
312
+ ```bash
313
+ curl http://localhost:9464/metrics
314
+ ```
315
+ 2. You should see output like:
316
+ ```
317
+ # HELP claude_tokens_total Total number of tokens used
318
+ # TYPE claude_tokens_total counter
319
+ claude_tokens_total{type="input",model="claude-sonnet-4"} 1234
320
+ claude_tokens_total{type="output",model="claude-sonnet-4"} 567
321
+ ...
322
+ ```
323
+
324
+ #### Verify in Prometheus:
325
+
326
+ 1. Open http://localhost:9090
327
+ 2. In the query box, type: `claude_tokens_total`
328
+ 3. Click "Execute"
329
+ 4. You should see your metrics data
330
+
331
+ If you see "No data points found", wait a minute and try again - Prometheus scrapes every 15 seconds.
332
+
333
+ ### Step 6: Set Up Grafana Dashboard
334
+
335
+ #### First-time Grafana Login:
336
+
337
+ 1. Open http://localhost:3000
338
+ 2. Login with:
339
+ - Username: `admin`
340
+ - Password: `admin`
341
+ 3. You'll be prompted to change the password (you can skip this for local testing)
342
+
343
+ #### Import the Dashboard:
344
+
345
+ **Method 1: Auto-provisioned (if using docker-compose)**
346
+
347
+ The dashboard should already be available:
348
+ 1. Click the hamburger menu (☰) on the left
349
+ 2. Click "Dashboards"
350
+ 3. Look for "Claude Usage Dashboard"
351
+
352
+ **Method 2: Manual Import**
353
+
354
+ 1. Click the hamburger menu (☰) on the left
355
+ 2. Click "Dashboards"
356
+ 3. Click "New" → "Import"
357
+ 4. Either:
358
+ - Click "Upload JSON file" and select `grafana/claude-usage-dashboard.json`
359
+ - Or paste the contents of the JSON file
360
+ 5. Click "Load"
361
+ 6. Select "Prometheus" as the data source
362
+ 7. Click "Import"
363
+
364
+ ### Step 7: Understanding the Dashboard
365
+
366
+ The dashboard shows several panels:
367
+
368
+ | Panel | What It Shows |
369
+ |-------|---------------|
370
+ | **Total Tokens** | Cumulative token count across all sessions |
371
+ | **Total Cost (USD)** | How much you've spent on Claude API |
372
+ | **Total API Requests** | Number of API calls made |
373
+ | **Total Sessions** | Number of OpenCode sessions |
374
+ | **Token Rate by Type** | Input vs output tokens over time |
375
+ | **Cost Rate by Model** | Spending per model (Opus, Sonnet, etc.) |
376
+ | **API Request Latency** | How fast Claude responds (p50, p95, p99) |
377
+ | **API Requests by Status** | Success vs error rates |
378
+ | **Top 10 Tools** | Most frequently used tools (Read, Edit, Bash, etc.) |
379
+ | **Tool Execution Latency** | How long each tool takes |
380
+
381
+ ### Step 8: Test the Complete Pipeline
382
+
383
+ Let's verify everything works end-to-end:
384
+
385
+ ```bash
386
+ # 1. Make sure environment is set
387
+ export CLAUDE_TRACKER_PUSHGATEWAY_URL=http://localhost:9091
388
+ export CLAUDE_TRACKER_VERBOSE=1
389
+
390
+ # 2. Start OpenCode and make some requests
391
+ opencode
392
+
393
+ # 3. In OpenCode, ask Claude something like:
394
+ # "What is 2 + 2?"
395
+ # "Read the README.md file"
396
+
397
+ # 4. Exit OpenCode (this flushes metrics)
398
+ ```
399
+
400
+ Now check your data:
401
+
402
+ 1. **Pushgateway** (http://localhost:9091): Should show new metrics
403
+ 2. **Prometheus** (http://localhost:9090): Query `claude_sessions_total` - should show at least 1
404
+ 3. **Grafana** (http://localhost:3000): Dashboard should show updated graphs
405
+
406
+ ### Prometheus Metrics Reference
407
+
408
+ | Metric | Type | Labels | Description |
409
+ |--------|------|--------|-------------|
410
+ | `claude_tokens_total` | Counter | `type`, `model` | Total tokens by type (input, output, cache_read, cache_creation) |
411
+ | `claude_cost_usd_total` | Counter | `model` | Total cost in USD |
412
+ | `claude_api_requests_total` | Counter | `model`, `status` | API request count by status (success/error) |
413
+ | `claude_sessions_total` | Counter | - | Total session count |
414
+ | `claude_tool_invocations_total` | Counter | `tool`, `status` | Tool invocations by status |
415
+ | `claude_api_request_duration_seconds` | Histogram | `model` | API request latency |
416
+ | `claude_tool_duration_seconds` | Histogram | `tool` | Tool execution latency |
417
+ | `claude_session_tokens` | Gauge | `type` | Current session token counts |
418
+ | `claude_session_cost_usd` | Gauge | - | Current session cost |
419
+
420
+ ### Example Prometheus Queries
421
+
422
+ Try these queries in Prometheus (http://localhost:9090):
423
+
424
+ ```promql
425
+ # Total tokens used (all time)
426
+ sum(claude_tokens_total)
427
+
428
+ # Total tokens in the last hour
429
+ sum(increase(claude_tokens_total[1h]))
430
+
431
+ # Current cost in USD
432
+ sum(claude_cost_usd_total)
433
+
434
+ # Cost rate by model ($ per minute)
435
+ sum(rate(claude_cost_usd_total[5m])) by (model) * 60
436
+
437
+ # API request success rate (percentage)
438
+ sum(rate(claude_api_requests_total{status="success"}[5m])) /
439
+ sum(rate(claude_api_requests_total[5m])) * 100
440
+
441
+ # 95th percentile API latency (seconds)
442
+ histogram_quantile(0.95, sum(rate(claude_api_request_duration_seconds_bucket[5m])) by (le))
443
+
444
+ # Top 5 most used tools
445
+ topk(5, sum(claude_tool_invocations_total) by (tool))
446
+
447
+ # Average tokens per request
448
+ sum(rate(claude_tokens_total[5m])) / sum(rate(claude_api_requests_total[5m]))
449
+ ```
450
+
451
+ ### Troubleshooting
452
+
453
+ #### "No data" in Grafana
454
+
455
+ 1. **Check Prometheus is receiving data**:
456
+ - Go to http://localhost:9090
457
+ - Query: `up` - should show `1` for all targets
458
+ - Query: `claude_sessions_total` - should return data
459
+
460
+ 2. **Check Pushgateway has metrics**:
461
+ - Go to http://localhost:9091
462
+ - Look for metrics under the job name
463
+
464
+ 3. **Verify environment variables**:
465
+ ```bash
466
+ echo $CLAUDE_TRACKER_PUSHGATEWAY_URL
467
+ # Should output: http://localhost:9091
468
+ ```
469
+
470
+ 4. **Check plugin logs** (if CLAUDE_TRACKER_VERBOSE=1):
471
+ - Look for "Pushed metrics to Pushgateway" messages
472
+
473
+ #### Prometheus can't scrape metrics
474
+
475
+ 1. **Check if metrics server is running**:
476
+ ```bash
477
+ curl http://localhost:9464/metrics
478
+ # Should return Prometheus-formatted metrics
479
+ ```
480
+
481
+ 2. **On Linux**, you may need to update `prometheus/prometheus.yml`:
482
+ ```yaml
483
+ # Change from:
484
+ - targets: ['host.docker.internal:9464']
485
+ # To your host IP:
486
+ - targets: ['172.17.0.1:9464']
487
+ ```
488
+ Then restart Prometheus:
489
+ ```bash
490
+ docker compose restart prometheus
491
+ ```
492
+
493
+ #### Services won't start
494
+
495
+ 1. **Port conflicts** - Check if ports are in use:
496
+ ```bash
497
+ lsof -i :9090 # Prometheus
498
+ lsof -i :9091 # Pushgateway
499
+ lsof -i :3000 # Grafana
500
+ ```
501
+
502
+ 2. **Docker issues** - Reset and try again:
503
+ ```bash
504
+ docker compose down -v
505
+ docker compose up -d
506
+ ```
507
+
508
+ #### Metrics are stale or not updating
509
+
510
+ 1. **Force a flush** in OpenCode by exiting the session
511
+ 2. **Check Pushgateway interval**:
512
+ ```bash
513
+ export CLAUDE_TRACKER_PUSHGATEWAY_INTERVAL=5000 # Push every 5 seconds
514
+ ```
515
+
516
+ ### Stopping the Monitoring Stack
517
+
518
+ When you're done:
519
+
520
+ ```bash
521
+ # Stop all services (keeps data)
522
+ docker compose down
523
+
524
+ # Stop and remove all data
525
+ docker compose down -v
526
+ ```
527
+
528
+ ### Advanced: Running in Production
529
+
530
+ For production use, consider:
531
+
532
+ 1. **Persistent storage**: The docker-compose already includes volumes for data persistence
533
+
534
+ 2. **Security**: Change default Grafana password:
535
+ ```yaml
536
+ # In docker-compose.yml
537
+ environment:
538
+ - GF_SECURITY_ADMIN_PASSWORD=your-secure-password
539
+ ```
540
+
541
+ 3. **Remote Pushgateway**: Point to your production Pushgateway:
542
+ ```bash
543
+ export CLAUDE_TRACKER_PUSHGATEWAY_URL=https://pushgateway.yourcompany.com
544
+ ```
545
+
546
+ 4. **Alerting**: Set up Grafana alerts for cost thresholds:
547
+ - Go to Dashboard → Edit panel → Alert tab
548
+ - Create alert when `claude_cost_usd_total > 100`
549
+
550
+ ## License
551
+
552
+ MIT
package/dist/cli.d.ts ADDED
@@ -0,0 +1,11 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * CLI utility for viewing Claude usage statistics
4
+ *
5
+ * Usage:
6
+ * npx opencode-plugin-claude-tracker report
7
+ * npx opencode-plugin-claude-tracker sessions [limit]
8
+ * npx opencode-plugin-claude-tracker export [format]
9
+ */
10
+ export {};
11
+ //# sourceMappingURL=cli.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":";AACA;;;;;;;GAOG"}