opencode-token-tracker 1.0.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 +21 -0
- package/README.md +119 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +218 -0
- package/package.json +51 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 tongshuanglong
|
|
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,119 @@
|
|
|
1
|
+
# opencode-token-tracker
|
|
2
|
+
|
|
3
|
+
Real-time token usage and cost tracking plugin for [OpenCode](https://opencode.ai).
|
|
4
|
+
|
|
5
|
+

|
|
6
|
+
|
|
7
|
+
## Features
|
|
8
|
+
|
|
9
|
+
- **Real-time Toast notifications** - See token usage and cost after each AI response
|
|
10
|
+
- **Session statistics** - Track cumulative usage across your entire session
|
|
11
|
+
- **Cost calculation** - Automatic cost estimation based on model pricing
|
|
12
|
+
- **JSONL logging** - All usage data saved locally for analysis
|
|
13
|
+
- **Multi-model support** - Claude, GPT, DeepSeek, Gemini, and more
|
|
14
|
+
|
|
15
|
+
## Installation
|
|
16
|
+
|
|
17
|
+
Add to your OpenCode config file (`~/.config/opencode/opencode.json`):
|
|
18
|
+
|
|
19
|
+
```json
|
|
20
|
+
{
|
|
21
|
+
"$schema": "https://opencode.ai/config.json",
|
|
22
|
+
"plugin": ["opencode-token-tracker"]
|
|
23
|
+
}
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
Restart OpenCode and the plugin will be automatically installed.
|
|
27
|
+
|
|
28
|
+
## Usage
|
|
29
|
+
|
|
30
|
+
Once installed, you'll see Toast notifications after each AI response:
|
|
31
|
+
|
|
32
|
+
```
|
|
33
|
+
12.5K tokens
|
|
34
|
+
$0.023 | Session: $0.156
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
When a session becomes idle, you'll see a summary:
|
|
38
|
+
|
|
39
|
+
```
|
|
40
|
+
Session: 45.2K tokens
|
|
41
|
+
$0.156 | 8 msgs | 5min
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
## Log Files
|
|
45
|
+
|
|
46
|
+
Token usage is logged to:
|
|
47
|
+
|
|
48
|
+
```
|
|
49
|
+
~/.config/opencode/logs/token-tracker/tokens.jsonl
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
Each line is a JSON object:
|
|
53
|
+
|
|
54
|
+
```json
|
|
55
|
+
{
|
|
56
|
+
"type": "tokens",
|
|
57
|
+
"sessionId": "ses_xxx",
|
|
58
|
+
"messageId": "msg_xxx",
|
|
59
|
+
"agent": "build",
|
|
60
|
+
"model": "claude-opus-4.5",
|
|
61
|
+
"provider": "github-copilot",
|
|
62
|
+
"input": 1500,
|
|
63
|
+
"output": 350,
|
|
64
|
+
"reasoning": 0,
|
|
65
|
+
"cacheRead": 5000,
|
|
66
|
+
"cacheWrite": 0,
|
|
67
|
+
"cost": 0.0234,
|
|
68
|
+
"_ts": 1234567890123
|
|
69
|
+
}
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
## Supported Models
|
|
73
|
+
|
|
74
|
+
| Provider | Models |
|
|
75
|
+
|----------|--------|
|
|
76
|
+
| Anthropic | Claude Opus 4.5, Sonnet 4/4.5, Haiku 4/4.5 |
|
|
77
|
+
| OpenAI | GPT-5.x, GPT-4.x, o1, o3 |
|
|
78
|
+
| DeepSeek | deepseek-chat, deepseek-reasoner |
|
|
79
|
+
| Google | Gemini 2.x, 3.x |
|
|
80
|
+
|
|
81
|
+
Unknown models use a default pricing estimate.
|
|
82
|
+
|
|
83
|
+
## Configuration
|
|
84
|
+
|
|
85
|
+
Currently the plugin works out of the box with no configuration needed.
|
|
86
|
+
|
|
87
|
+
Future versions may support:
|
|
88
|
+
- Custom pricing overrides
|
|
89
|
+
- Toast display options
|
|
90
|
+
- Export formats
|
|
91
|
+
|
|
92
|
+
## Development
|
|
93
|
+
|
|
94
|
+
```bash
|
|
95
|
+
# Clone the repo
|
|
96
|
+
git clone https://github.com/tongsh6/opencode-token-tracker.git
|
|
97
|
+
cd opencode-token-tracker
|
|
98
|
+
|
|
99
|
+
# Install dependencies
|
|
100
|
+
npm install
|
|
101
|
+
|
|
102
|
+
# Build
|
|
103
|
+
npm run build
|
|
104
|
+
|
|
105
|
+
# Link for local testing
|
|
106
|
+
npm link
|
|
107
|
+
cd ~/.config/opencode
|
|
108
|
+
npm link opencode-token-tracker
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
## License
|
|
112
|
+
|
|
113
|
+
MIT © [tongsh6](https://github.com/tongsh6)
|
|
114
|
+
|
|
115
|
+
## Related
|
|
116
|
+
|
|
117
|
+
- [OpenCode](https://opencode.ai) - The AI coding assistant
|
|
118
|
+
- [OpenCode Plugins](https://opencode.ai/docs/plugins) - Plugin documentation
|
|
119
|
+
- [oh-my-opencode](https://github.com/code-yeongyu/oh-my-opencode) - OpenCode enhancement plugin
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
import { appendFileSync, existsSync, mkdirSync } from "fs";
|
|
2
|
+
import { join } from "path";
|
|
3
|
+
import { homedir } from "os";
|
|
4
|
+
const LOG_DIR = join(homedir(), ".config", "opencode", "logs", "token-tracker");
|
|
5
|
+
const LOG_FILE = join(LOG_DIR, "tokens.jsonl");
|
|
6
|
+
// Prices as of 2026-02 (update as needed)
|
|
7
|
+
const PRICING = {
|
|
8
|
+
// Anthropic Claude
|
|
9
|
+
"claude-opus-4.5": { input: 15, output: 75, cacheRead: 1.5, cacheWrite: 18.75 },
|
|
10
|
+
"claude-sonnet-4.5": { input: 3, output: 15, cacheRead: 0.3, cacheWrite: 3.75 },
|
|
11
|
+
"claude-sonnet-4": { input: 3, output: 15, cacheRead: 0.3, cacheWrite: 3.75 },
|
|
12
|
+
"claude-haiku-4.5": { input: 0.8, output: 4, cacheRead: 0.08, cacheWrite: 1 },
|
|
13
|
+
"claude-haiku-4": { input: 0.8, output: 4, cacheRead: 0.08, cacheWrite: 1 },
|
|
14
|
+
// OpenAI GPT
|
|
15
|
+
"gpt-5.2": { input: 2.5, output: 10 },
|
|
16
|
+
"gpt-5.2-codex": { input: 3, output: 12 },
|
|
17
|
+
"gpt-5.1": { input: 2, output: 8 },
|
|
18
|
+
"gpt-5": { input: 5, output: 15 },
|
|
19
|
+
"gpt-4.1": { input: 2, output: 8 },
|
|
20
|
+
"gpt-4.1-mini": { input: 0.4, output: 1.6 },
|
|
21
|
+
"gpt-4.1-nano": { input: 0.1, output: 0.4 },
|
|
22
|
+
"gpt-4o": { input: 2.5, output: 10 },
|
|
23
|
+
"gpt-4o-mini": { input: 0.15, output: 0.6 },
|
|
24
|
+
"o3": { input: 10, output: 40 },
|
|
25
|
+
"o3-mini": { input: 1.1, output: 4.4 },
|
|
26
|
+
"o1": { input: 15, output: 60 },
|
|
27
|
+
"o1-mini": { input: 1.1, output: 4.4 },
|
|
28
|
+
// DeepSeek
|
|
29
|
+
"deepseek-chat": { input: 0.14, output: 0.28, cacheRead: 0.014 },
|
|
30
|
+
"deepseek-reasoner": { input: 0.55, output: 2.19, cacheRead: 0.055 },
|
|
31
|
+
// Google Gemini
|
|
32
|
+
"gemini-3-pro": { input: 1.25, output: 5 },
|
|
33
|
+
"gemini-3-pro-preview": { input: 1.25, output: 5 },
|
|
34
|
+
"gemini-3-flash": { input: 0.1, output: 0.4 },
|
|
35
|
+
"gemini-2.5-pro": { input: 1.25, output: 5 },
|
|
36
|
+
"gemini-2.5-flash": { input: 0.075, output: 0.3 },
|
|
37
|
+
"gemini-2.0-flash": { input: 0.1, output: 0.4 },
|
|
38
|
+
// Fallback for unknown models
|
|
39
|
+
"_default": { input: 1, output: 4 },
|
|
40
|
+
};
|
|
41
|
+
function getModelPricing(model) {
|
|
42
|
+
// Try exact match first
|
|
43
|
+
if (PRICING[model])
|
|
44
|
+
return PRICING[model];
|
|
45
|
+
// Try partial match (e.g., "claude-opus-4.5" matches "claude-opus-4.5-xxx")
|
|
46
|
+
const modelLower = model.toLowerCase();
|
|
47
|
+
for (const [key, pricing] of Object.entries(PRICING)) {
|
|
48
|
+
if (key !== "_default" && modelLower.includes(key.toLowerCase())) {
|
|
49
|
+
return pricing;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return PRICING["_default"];
|
|
53
|
+
}
|
|
54
|
+
function calculateCost(model, input, output, cacheRead = 0, cacheWrite = 0) {
|
|
55
|
+
const pricing = getModelPricing(model);
|
|
56
|
+
// Billable input = total input - cache read (cached tokens are charged at cache rate)
|
|
57
|
+
const billableInput = Math.max(0, input - cacheRead);
|
|
58
|
+
const inputCost = (billableInput / 1_000_000) * pricing.input;
|
|
59
|
+
const outputCost = (output / 1_000_000) * pricing.output;
|
|
60
|
+
const cacheReadCost = (cacheRead / 1_000_000) * (pricing.cacheRead ?? pricing.input * 0.1);
|
|
61
|
+
const cacheWriteCost = (cacheWrite / 1_000_000) * (pricing.cacheWrite ?? pricing.input * 1.25);
|
|
62
|
+
return inputCost + outputCost + cacheReadCost + cacheWriteCost;
|
|
63
|
+
}
|
|
64
|
+
const sessionStats = new Map();
|
|
65
|
+
function getOrCreateSessionStats(sessionId) {
|
|
66
|
+
if (!sessionStats.has(sessionId)) {
|
|
67
|
+
sessionStats.set(sessionId, {
|
|
68
|
+
totalInput: 0,
|
|
69
|
+
totalOutput: 0,
|
|
70
|
+
totalReasoning: 0,
|
|
71
|
+
totalCacheRead: 0,
|
|
72
|
+
totalCacheWrite: 0,
|
|
73
|
+
totalCost: 0,
|
|
74
|
+
messageCount: 0,
|
|
75
|
+
startTime: Date.now(),
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
return sessionStats.get(sessionId);
|
|
79
|
+
}
|
|
80
|
+
function formatCost(cost) {
|
|
81
|
+
if (cost < 0.01)
|
|
82
|
+
return `$${cost.toFixed(4)}`;
|
|
83
|
+
if (cost < 1)
|
|
84
|
+
return `$${cost.toFixed(3)}`;
|
|
85
|
+
return `$${cost.toFixed(2)}`;
|
|
86
|
+
}
|
|
87
|
+
function formatTokens(tokens) {
|
|
88
|
+
if (tokens >= 1_000_000)
|
|
89
|
+
return `${(tokens / 1_000_000).toFixed(1)}M`;
|
|
90
|
+
if (tokens >= 1_000)
|
|
91
|
+
return `${(tokens / 1_000).toFixed(1)}K`;
|
|
92
|
+
return tokens.toString();
|
|
93
|
+
}
|
|
94
|
+
// ============================================================================
|
|
95
|
+
// Deduplication
|
|
96
|
+
// ============================================================================
|
|
97
|
+
const seen = new Set();
|
|
98
|
+
function isDuplicate(key) {
|
|
99
|
+
if (seen.has(key))
|
|
100
|
+
return true;
|
|
101
|
+
seen.add(key);
|
|
102
|
+
// Cleanup old entries to prevent memory leak
|
|
103
|
+
if (seen.size > 10000) {
|
|
104
|
+
const entries = Array.from(seen);
|
|
105
|
+
entries.slice(0, 5000).forEach(k => seen.delete(k));
|
|
106
|
+
}
|
|
107
|
+
return false;
|
|
108
|
+
}
|
|
109
|
+
// ============================================================================
|
|
110
|
+
// Logging
|
|
111
|
+
// ============================================================================
|
|
112
|
+
function ensureLogDir() {
|
|
113
|
+
if (!existsSync(LOG_DIR)) {
|
|
114
|
+
mkdirSync(LOG_DIR, { recursive: true });
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
function logJson(data) {
|
|
118
|
+
ensureLogDir();
|
|
119
|
+
const entry = JSON.stringify({ ...data, _ts: Date.now() }) + "\n";
|
|
120
|
+
appendFileSync(LOG_FILE, entry);
|
|
121
|
+
}
|
|
122
|
+
export const TokenTrackerPlugin = async ({ directory, client }) => {
|
|
123
|
+
logJson({ type: "init", directory });
|
|
124
|
+
return {
|
|
125
|
+
event: async ({ event }) => {
|
|
126
|
+
try {
|
|
127
|
+
// Handle message updates (token tracking)
|
|
128
|
+
if (event.type === "message.updated") {
|
|
129
|
+
const props = event.properties;
|
|
130
|
+
const info = props?.info;
|
|
131
|
+
if (!info?.tokens)
|
|
132
|
+
return;
|
|
133
|
+
const messageId = info.id;
|
|
134
|
+
const sessionId = info.sessionID;
|
|
135
|
+
if (!messageId || !sessionId)
|
|
136
|
+
return;
|
|
137
|
+
const input = info.tokens.input ?? 0;
|
|
138
|
+
const output = info.tokens.output ?? 0;
|
|
139
|
+
const reasoning = info.tokens.reasoning ?? 0;
|
|
140
|
+
const cacheRead = info.tokens.cache?.read ?? 0;
|
|
141
|
+
const cacheWrite = info.tokens.cache?.write ?? 0;
|
|
142
|
+
const hasTokens = input > 0 || output > 0;
|
|
143
|
+
if (!hasTokens)
|
|
144
|
+
return;
|
|
145
|
+
const dedupeKey = `${messageId}-${input}-${output}`;
|
|
146
|
+
if (isDuplicate(dedupeKey))
|
|
147
|
+
return;
|
|
148
|
+
const model = info.model?.modelID ?? info.modelID ?? "unknown";
|
|
149
|
+
const provider = info.model?.providerID ?? info.providerID ?? "unknown";
|
|
150
|
+
const cost = calculateCost(model, input, output, cacheRead, cacheWrite);
|
|
151
|
+
// Update session stats
|
|
152
|
+
const stats = getOrCreateSessionStats(sessionId);
|
|
153
|
+
stats.totalInput += input;
|
|
154
|
+
stats.totalOutput += output;
|
|
155
|
+
stats.totalReasoning += reasoning;
|
|
156
|
+
stats.totalCacheRead += cacheRead;
|
|
157
|
+
stats.totalCacheWrite += cacheWrite;
|
|
158
|
+
stats.totalCost += cost;
|
|
159
|
+
stats.messageCount += 1;
|
|
160
|
+
// Log to file
|
|
161
|
+
logJson({
|
|
162
|
+
type: "tokens",
|
|
163
|
+
sessionId,
|
|
164
|
+
messageId,
|
|
165
|
+
role: info.role,
|
|
166
|
+
agent: info.agent,
|
|
167
|
+
model,
|
|
168
|
+
provider,
|
|
169
|
+
input,
|
|
170
|
+
output,
|
|
171
|
+
reasoning,
|
|
172
|
+
cacheRead,
|
|
173
|
+
cacheWrite,
|
|
174
|
+
cost,
|
|
175
|
+
});
|
|
176
|
+
// Show toast for this message
|
|
177
|
+
const totalTokens = input + output;
|
|
178
|
+
try {
|
|
179
|
+
await client.tui.showToast({
|
|
180
|
+
body: {
|
|
181
|
+
title: `${formatTokens(totalTokens)} tokens`,
|
|
182
|
+
message: `${formatCost(cost)} | Session: ${formatCost(stats.totalCost)}`,
|
|
183
|
+
variant: "info",
|
|
184
|
+
duration: 3000,
|
|
185
|
+
},
|
|
186
|
+
});
|
|
187
|
+
}
|
|
188
|
+
catch { }
|
|
189
|
+
}
|
|
190
|
+
// Handle session idle (show summary)
|
|
191
|
+
if (event.type === "session.idle") {
|
|
192
|
+
const props = event.properties;
|
|
193
|
+
const sessionId = props?.sessionID;
|
|
194
|
+
if (!sessionId)
|
|
195
|
+
return;
|
|
196
|
+
const stats = sessionStats.get(sessionId);
|
|
197
|
+
if (!stats || stats.messageCount === 0)
|
|
198
|
+
return;
|
|
199
|
+
const duration = Math.round((Date.now() - stats.startTime) / 1000 / 60);
|
|
200
|
+
const totalTokens = stats.totalInput + stats.totalOutput;
|
|
201
|
+
try {
|
|
202
|
+
await client.tui.showToast({
|
|
203
|
+
body: {
|
|
204
|
+
title: `Session: ${formatTokens(totalTokens)} tokens`,
|
|
205
|
+
message: `${formatCost(stats.totalCost)} | ${stats.messageCount} msgs | ${duration}min`,
|
|
206
|
+
variant: "info",
|
|
207
|
+
duration: 5000,
|
|
208
|
+
},
|
|
209
|
+
});
|
|
210
|
+
}
|
|
211
|
+
catch { }
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
catch { }
|
|
215
|
+
},
|
|
216
|
+
};
|
|
217
|
+
};
|
|
218
|
+
export default TokenTrackerPlugin;
|
package/package.json
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "opencode-token-tracker",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Real-time token usage and cost tracking plugin for OpenCode with Toast notifications",
|
|
5
|
+
"main": "dist/index.js",
|
|
6
|
+
"types": "dist/index.d.ts",
|
|
7
|
+
"type": "module",
|
|
8
|
+
"scripts": {
|
|
9
|
+
"build": "tsc",
|
|
10
|
+
"prepublishOnly": "npm run build"
|
|
11
|
+
},
|
|
12
|
+
"keywords": [
|
|
13
|
+
"opencode",
|
|
14
|
+
"plugin",
|
|
15
|
+
"token",
|
|
16
|
+
"usage",
|
|
17
|
+
"cost",
|
|
18
|
+
"tracking",
|
|
19
|
+
"ai",
|
|
20
|
+
"llm",
|
|
21
|
+
"claude",
|
|
22
|
+
"gpt",
|
|
23
|
+
"anthropic",
|
|
24
|
+
"openai"
|
|
25
|
+
],
|
|
26
|
+
"author": "tongsh6",
|
|
27
|
+
"license": "MIT",
|
|
28
|
+
"repository": {
|
|
29
|
+
"type": "git",
|
|
30
|
+
"url": "git+https://github.com/tongsh6/opencode-token-tracker.git"
|
|
31
|
+
},
|
|
32
|
+
"bugs": {
|
|
33
|
+
"url": "https://github.com/tongsh6/opencode-token-tracker/issues"
|
|
34
|
+
},
|
|
35
|
+
"homepage": "https://github.com/tongsh6/opencode-token-tracker#readme",
|
|
36
|
+
"dependencies": {
|
|
37
|
+
"@opencode-ai/plugin": "latest"
|
|
38
|
+
},
|
|
39
|
+
"devDependencies": {
|
|
40
|
+
"@types/node": "^20.0.0",
|
|
41
|
+
"typescript": "^5.0.0"
|
|
42
|
+
},
|
|
43
|
+
"files": [
|
|
44
|
+
"dist",
|
|
45
|
+
"README.md",
|
|
46
|
+
"LICENSE"
|
|
47
|
+
],
|
|
48
|
+
"engines": {
|
|
49
|
+
"node": ">=18.0.0"
|
|
50
|
+
}
|
|
51
|
+
}
|