mcp-rubber-duck 1.5.2 ā 1.6.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/.claude/agents/pricing-updater.md +111 -0
- package/.claude/commands/update-pricing.md +22 -0
- package/CHANGELOG.md +7 -0
- package/dist/config/types.d.ts +72 -0
- package/dist/config/types.d.ts.map +1 -1
- package/dist/config/types.js +8 -0
- package/dist/config/types.js.map +1 -1
- package/dist/data/default-pricing.d.ts +18 -0
- package/dist/data/default-pricing.d.ts.map +1 -0
- package/dist/data/default-pricing.js +307 -0
- package/dist/data/default-pricing.js.map +1 -0
- package/dist/providers/enhanced-manager.d.ts +2 -1
- package/dist/providers/enhanced-manager.d.ts.map +1 -1
- package/dist/providers/enhanced-manager.js +20 -2
- package/dist/providers/enhanced-manager.js.map +1 -1
- package/dist/providers/manager.d.ts +3 -1
- package/dist/providers/manager.d.ts.map +1 -1
- package/dist/providers/manager.js +12 -1
- package/dist/providers/manager.js.map +1 -1
- package/dist/server.d.ts +2 -0
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +35 -4
- package/dist/server.js.map +1 -1
- package/dist/services/pricing.d.ts +56 -0
- package/dist/services/pricing.d.ts.map +1 -0
- package/dist/services/pricing.js +124 -0
- package/dist/services/pricing.js.map +1 -0
- package/dist/services/usage.d.ts +48 -0
- package/dist/services/usage.d.ts.map +1 -0
- package/dist/services/usage.js +243 -0
- package/dist/services/usage.js.map +1 -0
- package/dist/tools/get-usage-stats.d.ts +8 -0
- package/dist/tools/get-usage-stats.d.ts.map +1 -0
- package/dist/tools/get-usage-stats.js +92 -0
- package/dist/tools/get-usage-stats.js.map +1 -0
- package/package.json +1 -1
- package/src/config/types.ts +51 -0
- package/src/data/default-pricing.ts +368 -0
- package/src/providers/enhanced-manager.ts +41 -4
- package/src/providers/manager.ts +22 -1
- package/src/server.ts +42 -4
- package/src/services/pricing.ts +155 -0
- package/src/services/usage.ts +293 -0
- package/src/tools/get-usage-stats.ts +109 -0
- package/tests/pricing.test.ts +335 -0
- package/tests/tools/get-usage-stats.test.ts +236 -0
- package/tests/usage.test.ts +661 -0
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
import { ModelPricing, PricingConfig } from '../config/types.js';
|
|
2
|
+
import { DEFAULT_PRICING } from '../data/default-pricing.js';
|
|
3
|
+
import { logger } from '../utils/logger.js';
|
|
4
|
+
|
|
5
|
+
export interface CostCalculation {
|
|
6
|
+
inputCost: number;
|
|
7
|
+
outputCost: number;
|
|
8
|
+
totalCost: number;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Provider name aliases.
|
|
13
|
+
* Maps common user-provided names to canonical provider names in pricing data.
|
|
14
|
+
*/
|
|
15
|
+
const PROVIDER_ALIASES: Record<string, string> = {
|
|
16
|
+
gemini: 'google',
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* PricingService manages token pricing data.
|
|
21
|
+
*
|
|
22
|
+
* It merges hardcoded default pricing with optional user config overrides.
|
|
23
|
+
* User overrides take precedence over defaults.
|
|
24
|
+
*/
|
|
25
|
+
export class PricingService {
|
|
26
|
+
private pricing: PricingConfig;
|
|
27
|
+
|
|
28
|
+
constructor(configPricing?: PricingConfig) {
|
|
29
|
+
this.pricing = this.mergePricing(DEFAULT_PRICING, configPricing);
|
|
30
|
+
const providerCount = Object.keys(this.pricing).length;
|
|
31
|
+
const modelCount = Object.values(this.pricing).reduce(
|
|
32
|
+
(acc, models) => acc + Object.keys(models).length,
|
|
33
|
+
0
|
|
34
|
+
);
|
|
35
|
+
logger.debug(`PricingService initialized with ${providerCount} providers, ${modelCount} models`);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Deep merge pricing configs. Overrides take precedence.
|
|
40
|
+
*/
|
|
41
|
+
private mergePricing(defaults: PricingConfig, overrides?: PricingConfig): PricingConfig {
|
|
42
|
+
const result: PricingConfig = {};
|
|
43
|
+
|
|
44
|
+
// Deep copy all defaults
|
|
45
|
+
for (const [provider, models] of Object.entries(defaults)) {
|
|
46
|
+
result[provider] = {};
|
|
47
|
+
for (const [model, pricing] of Object.entries(models)) {
|
|
48
|
+
result[provider][model] = { ...pricing };
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
if (!overrides) {
|
|
53
|
+
return result;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// Apply overrides
|
|
57
|
+
for (const [provider, models] of Object.entries(overrides)) {
|
|
58
|
+
if (!result[provider]) {
|
|
59
|
+
result[provider] = {};
|
|
60
|
+
}
|
|
61
|
+
for (const [model, pricing] of Object.entries(models)) {
|
|
62
|
+
result[provider][model] = { ...pricing };
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
return result;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Resolve provider name, checking for aliases.
|
|
71
|
+
* First checks if provider exists directly, then checks aliases.
|
|
72
|
+
*/
|
|
73
|
+
private resolveProvider(provider: string): string {
|
|
74
|
+
// Direct match takes precedence
|
|
75
|
+
if (this.pricing[provider]) {
|
|
76
|
+
return provider;
|
|
77
|
+
}
|
|
78
|
+
// Check aliases
|
|
79
|
+
return PROVIDER_ALIASES[provider] || provider;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Get pricing for a specific provider and model.
|
|
84
|
+
* Returns undefined if pricing is not configured.
|
|
85
|
+
* Supports provider aliases (e.g., "gemini" -> "google").
|
|
86
|
+
*/
|
|
87
|
+
getPricing(provider: string, model: string): ModelPricing | undefined {
|
|
88
|
+
const resolvedProvider = this.resolveProvider(provider);
|
|
89
|
+
return this.pricing[resolvedProvider]?.[model];
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Calculate the cost for a given number of tokens.
|
|
94
|
+
* Returns null if pricing is not configured for the provider/model.
|
|
95
|
+
*/
|
|
96
|
+
calculateCost(
|
|
97
|
+
provider: string,
|
|
98
|
+
model: string,
|
|
99
|
+
promptTokens: number,
|
|
100
|
+
completionTokens: number
|
|
101
|
+
): CostCalculation | null {
|
|
102
|
+
const pricing = this.getPricing(provider, model);
|
|
103
|
+
if (!pricing) {
|
|
104
|
+
return null;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
const inputCost = (promptTokens / 1_000_000) * pricing.inputPricePerMillion;
|
|
108
|
+
const outputCost = (completionTokens / 1_000_000) * pricing.outputPricePerMillion;
|
|
109
|
+
|
|
110
|
+
return {
|
|
111
|
+
inputCost,
|
|
112
|
+
outputCost,
|
|
113
|
+
totalCost: inputCost + outputCost,
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Check if pricing is configured for a provider/model combination.
|
|
119
|
+
* Supports provider aliases.
|
|
120
|
+
*/
|
|
121
|
+
hasPricingFor(provider: string, model: string): boolean {
|
|
122
|
+
return this.getPricing(provider, model) !== undefined;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Get all pricing data (for debugging/display).
|
|
127
|
+
* Returns a deep copy to prevent external mutation.
|
|
128
|
+
*/
|
|
129
|
+
getAllPricing(): PricingConfig {
|
|
130
|
+
const result: PricingConfig = {};
|
|
131
|
+
for (const [provider, models] of Object.entries(this.pricing)) {
|
|
132
|
+
result[provider] = {};
|
|
133
|
+
for (const [model, pricing] of Object.entries(models)) {
|
|
134
|
+
result[provider][model] = { ...pricing };
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
return result;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Get list of all configured providers.
|
|
142
|
+
*/
|
|
143
|
+
getProviders(): string[] {
|
|
144
|
+
return Object.keys(this.pricing);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* Get list of all models for a provider.
|
|
149
|
+
* Supports provider aliases.
|
|
150
|
+
*/
|
|
151
|
+
getModelsForProvider(provider: string): string[] {
|
|
152
|
+
const resolvedProvider = this.resolveProvider(provider);
|
|
153
|
+
return Object.keys(this.pricing[resolvedProvider] || {});
|
|
154
|
+
}
|
|
155
|
+
}
|
|
@@ -0,0 +1,293 @@
|
|
|
1
|
+
import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'fs';
|
|
2
|
+
import { join } from 'path';
|
|
3
|
+
import { homedir } from 'os';
|
|
4
|
+
import {
|
|
5
|
+
UsageData,
|
|
6
|
+
DailyUsage,
|
|
7
|
+
ModelUsageStats,
|
|
8
|
+
UsageTimePeriod,
|
|
9
|
+
UsageStatsResult,
|
|
10
|
+
} from '../config/types.js';
|
|
11
|
+
import { PricingService } from './pricing.js';
|
|
12
|
+
import { logger } from '../utils/logger.js';
|
|
13
|
+
|
|
14
|
+
const USAGE_DATA_VERSION = 1;
|
|
15
|
+
const DEFAULT_DEBOUNCE_MS = 5000;
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* UsageService tracks token usage per model per day.
|
|
19
|
+
*
|
|
20
|
+
* Data is stored in ~/.mcp-rubber-duck/data/usage.json
|
|
21
|
+
* Writes are debounced to avoid excessive disk I/O.
|
|
22
|
+
*/
|
|
23
|
+
export class UsageService {
|
|
24
|
+
private usagePath: string;
|
|
25
|
+
private data: UsageData;
|
|
26
|
+
private pricingService: PricingService;
|
|
27
|
+
private pendingWrites: number = 0;
|
|
28
|
+
private writeDebounceTimer: ReturnType<typeof setTimeout> | null = null;
|
|
29
|
+
private debounceMs: number;
|
|
30
|
+
|
|
31
|
+
constructor(pricingService: PricingService, options?: { dataDir?: string; debounceMs?: number }) {
|
|
32
|
+
this.pricingService = pricingService;
|
|
33
|
+
this.debounceMs = options?.debounceMs ?? DEFAULT_DEBOUNCE_MS;
|
|
34
|
+
|
|
35
|
+
const dataDir = options?.dataDir ?? join(homedir(), '.mcp-rubber-duck', 'data');
|
|
36
|
+
this.ensureDirectoryExists(dataDir);
|
|
37
|
+
this.usagePath = join(dataDir, 'usage.json');
|
|
38
|
+
this.data = this.loadUsage();
|
|
39
|
+
|
|
40
|
+
logger.debug(`UsageService initialized, data path: ${this.usagePath}`);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
private ensureDirectoryExists(dir: string): void {
|
|
44
|
+
if (!existsSync(dir)) {
|
|
45
|
+
mkdirSync(dir, { recursive: true });
|
|
46
|
+
logger.debug(`Created data directory: ${dir}`);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
private loadUsage(): UsageData {
|
|
51
|
+
try {
|
|
52
|
+
if (existsSync(this.usagePath)) {
|
|
53
|
+
const raw = readFileSync(this.usagePath, 'utf-8');
|
|
54
|
+
const data = JSON.parse(raw) as UsageData;
|
|
55
|
+
|
|
56
|
+
// Validate structure
|
|
57
|
+
if (typeof data !== 'object' || data === null) {
|
|
58
|
+
throw new Error('Invalid usage data: not an object');
|
|
59
|
+
}
|
|
60
|
+
if (typeof data.daily !== 'object' || data.daily === null) {
|
|
61
|
+
throw new Error('Invalid usage data: missing daily object');
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
logger.debug(`Loaded usage data from ${this.usagePath}`);
|
|
65
|
+
return data;
|
|
66
|
+
}
|
|
67
|
+
} catch (error) {
|
|
68
|
+
logger.warn('Failed to load usage data, starting fresh:', error);
|
|
69
|
+
}
|
|
70
|
+
return { version: USAGE_DATA_VERSION, daily: {} };
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
private saveUsage(): void {
|
|
74
|
+
try {
|
|
75
|
+
writeFileSync(this.usagePath, JSON.stringify(this.data, null, 2));
|
|
76
|
+
logger.debug(`Saved usage data to ${this.usagePath}`);
|
|
77
|
+
} catch (error) {
|
|
78
|
+
logger.error('Failed to save usage data:', error);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
private scheduleSave(): void {
|
|
83
|
+
this.pendingWrites++;
|
|
84
|
+
if (this.writeDebounceTimer) {
|
|
85
|
+
clearTimeout(this.writeDebounceTimer);
|
|
86
|
+
}
|
|
87
|
+
this.writeDebounceTimer = setTimeout(() => {
|
|
88
|
+
this.saveUsage();
|
|
89
|
+
this.pendingWrites = 0;
|
|
90
|
+
this.writeDebounceTimer = null;
|
|
91
|
+
}, this.debounceMs);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
private getTodayKey(): string {
|
|
95
|
+
// Use local date to match getStats() behavior
|
|
96
|
+
const now = new Date();
|
|
97
|
+
const year = now.getFullYear();
|
|
98
|
+
const month = String(now.getMonth() + 1).padStart(2, '0');
|
|
99
|
+
const day = String(now.getDate()).padStart(2, '0');
|
|
100
|
+
return `${year}-${month}-${day}`;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Record usage for a provider/model.
|
|
105
|
+
*/
|
|
106
|
+
recordUsage(
|
|
107
|
+
provider: string,
|
|
108
|
+
model: string,
|
|
109
|
+
promptTokens: number,
|
|
110
|
+
completionTokens: number,
|
|
111
|
+
cacheHit: boolean = false,
|
|
112
|
+
error: boolean = false
|
|
113
|
+
): void {
|
|
114
|
+
const today = this.getTodayKey();
|
|
115
|
+
|
|
116
|
+
// Initialize nested structure if needed
|
|
117
|
+
if (!this.data.daily[today]) {
|
|
118
|
+
this.data.daily[today] = {};
|
|
119
|
+
}
|
|
120
|
+
if (!this.data.daily[today][provider]) {
|
|
121
|
+
this.data.daily[today][provider] = {};
|
|
122
|
+
}
|
|
123
|
+
if (!this.data.daily[today][provider][model]) {
|
|
124
|
+
this.data.daily[today][provider][model] = {
|
|
125
|
+
requests: 0,
|
|
126
|
+
promptTokens: 0,
|
|
127
|
+
completionTokens: 0,
|
|
128
|
+
cacheHits: 0,
|
|
129
|
+
errors: 0,
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const stats = this.data.daily[today][provider][model];
|
|
134
|
+
stats.requests++;
|
|
135
|
+
stats.promptTokens += promptTokens;
|
|
136
|
+
stats.completionTokens += completionTokens;
|
|
137
|
+
if (cacheHit) stats.cacheHits++;
|
|
138
|
+
if (error) stats.errors++;
|
|
139
|
+
|
|
140
|
+
logger.debug(
|
|
141
|
+
`Recorded usage: ${provider}/${model} +${promptTokens}/${completionTokens} tokens`
|
|
142
|
+
);
|
|
143
|
+
|
|
144
|
+
this.scheduleSave();
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* Get usage statistics for a time period.
|
|
149
|
+
*/
|
|
150
|
+
getStats(period: UsageTimePeriod): UsageStatsResult {
|
|
151
|
+
const today = new Date();
|
|
152
|
+
today.setHours(0, 0, 0, 0);
|
|
153
|
+
|
|
154
|
+
let startDate: Date;
|
|
155
|
+
switch (period) {
|
|
156
|
+
case 'today':
|
|
157
|
+
startDate = today;
|
|
158
|
+
break;
|
|
159
|
+
case '7d':
|
|
160
|
+
startDate = new Date(today.getTime() - 6 * 24 * 60 * 60 * 1000);
|
|
161
|
+
break;
|
|
162
|
+
case '30d':
|
|
163
|
+
startDate = new Date(today.getTime() - 29 * 24 * 60 * 60 * 1000);
|
|
164
|
+
break;
|
|
165
|
+
case 'all':
|
|
166
|
+
startDate = new Date(0);
|
|
167
|
+
break;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
const aggregated: DailyUsage = {};
|
|
171
|
+
const totals: ModelUsageStats = {
|
|
172
|
+
requests: 0,
|
|
173
|
+
promptTokens: 0,
|
|
174
|
+
completionTokens: 0,
|
|
175
|
+
cacheHits: 0,
|
|
176
|
+
errors: 0,
|
|
177
|
+
};
|
|
178
|
+
const costByProvider: Record<string, number> = {};
|
|
179
|
+
let totalCost = 0;
|
|
180
|
+
let hasCostData = false;
|
|
181
|
+
|
|
182
|
+
for (const [dateKey, dayData] of Object.entries(this.data.daily)) {
|
|
183
|
+
// Parse dateKey as local date (not UTC) to match getTodayKey() format
|
|
184
|
+
// dateKey is "YYYY-MM-DD", we need to parse it as local midnight
|
|
185
|
+
const [year, month, day] = dateKey.split('-').map(Number);
|
|
186
|
+
const date = new Date(year, month - 1, day); // month is 0-indexed
|
|
187
|
+
|
|
188
|
+
// Skip invalid dates or dates outside range
|
|
189
|
+
if (isNaN(date.getTime()) || date < startDate || date > today) continue;
|
|
190
|
+
|
|
191
|
+
for (const [provider, providerData] of Object.entries(dayData)) {
|
|
192
|
+
if (!aggregated[provider]) {
|
|
193
|
+
aggregated[provider] = {};
|
|
194
|
+
costByProvider[provider] = 0;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
for (const [model, stats] of Object.entries(providerData)) {
|
|
198
|
+
if (!aggregated[provider][model]) {
|
|
199
|
+
aggregated[provider][model] = {
|
|
200
|
+
requests: 0,
|
|
201
|
+
promptTokens: 0,
|
|
202
|
+
completionTokens: 0,
|
|
203
|
+
cacheHits: 0,
|
|
204
|
+
errors: 0,
|
|
205
|
+
};
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
const agg = aggregated[provider][model];
|
|
209
|
+
agg.requests += stats.requests;
|
|
210
|
+
agg.promptTokens += stats.promptTokens;
|
|
211
|
+
agg.completionTokens += stats.completionTokens;
|
|
212
|
+
agg.cacheHits += stats.cacheHits;
|
|
213
|
+
agg.errors += stats.errors;
|
|
214
|
+
|
|
215
|
+
totals.requests += stats.requests;
|
|
216
|
+
totals.promptTokens += stats.promptTokens;
|
|
217
|
+
totals.completionTokens += stats.completionTokens;
|
|
218
|
+
totals.cacheHits += stats.cacheHits;
|
|
219
|
+
totals.errors += stats.errors;
|
|
220
|
+
|
|
221
|
+
// Calculate cost if pricing available
|
|
222
|
+
const cost = this.pricingService.calculateCost(
|
|
223
|
+
provider,
|
|
224
|
+
model,
|
|
225
|
+
stats.promptTokens,
|
|
226
|
+
stats.completionTokens
|
|
227
|
+
);
|
|
228
|
+
if (cost) {
|
|
229
|
+
totalCost += cost.totalCost;
|
|
230
|
+
costByProvider[provider] += cost.totalCost;
|
|
231
|
+
hasCostData = true;
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
const result: UsageStatsResult = {
|
|
238
|
+
period,
|
|
239
|
+
startDate: this.formatDate(startDate),
|
|
240
|
+
endDate: this.formatDate(today),
|
|
241
|
+
usage: aggregated,
|
|
242
|
+
totals: {
|
|
243
|
+
...totals,
|
|
244
|
+
},
|
|
245
|
+
};
|
|
246
|
+
|
|
247
|
+
if (hasCostData) {
|
|
248
|
+
result.totals.estimatedCostUSD = totalCost;
|
|
249
|
+
result.costByProvider = costByProvider;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
return result;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
private formatDate(date: Date): string {
|
|
256
|
+
// Use local date components to match getTodayKey() and date filtering
|
|
257
|
+
const year = date.getFullYear();
|
|
258
|
+
const month = String(date.getMonth() + 1).padStart(2, '0');
|
|
259
|
+
const day = String(date.getDate()).padStart(2, '0');
|
|
260
|
+
return `${year}-${month}-${day}`;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/**
|
|
264
|
+
* Flush pending writes immediately. Call on shutdown.
|
|
265
|
+
*/
|
|
266
|
+
shutdown(): void {
|
|
267
|
+
if (this.writeDebounceTimer) {
|
|
268
|
+
clearTimeout(this.writeDebounceTimer);
|
|
269
|
+
this.writeDebounceTimer = null;
|
|
270
|
+
}
|
|
271
|
+
if (this.pendingWrites > 0) {
|
|
272
|
+
this.saveUsage();
|
|
273
|
+
this.pendingWrites = 0;
|
|
274
|
+
}
|
|
275
|
+
logger.debug('UsageService shutdown complete');
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/**
|
|
279
|
+
* Get raw usage data (for testing/debugging).
|
|
280
|
+
* Returns a deep copy to prevent external mutation.
|
|
281
|
+
*/
|
|
282
|
+
getRawData(): UsageData {
|
|
283
|
+
return JSON.parse(JSON.stringify(this.data)) as UsageData;
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/**
|
|
287
|
+
* Clear all usage data (for testing).
|
|
288
|
+
*/
|
|
289
|
+
clearData(): void {
|
|
290
|
+
this.data = { version: USAGE_DATA_VERSION, daily: {} };
|
|
291
|
+
this.scheduleSave();
|
|
292
|
+
}
|
|
293
|
+
}
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { UsageService } from '../services/usage.js';
|
|
2
|
+
import { UsageTimePeriod } from '../config/types.js';
|
|
3
|
+
import { duckArt } from '../utils/ascii-art.js';
|
|
4
|
+
import { logger } from '../utils/logger.js';
|
|
5
|
+
|
|
6
|
+
const VALID_PERIODS: UsageTimePeriod[] = ['today', '7d', '30d', 'all'];
|
|
7
|
+
|
|
8
|
+
export function getUsageStatsTool(
|
|
9
|
+
usageService: UsageService,
|
|
10
|
+
args: Record<string, unknown>
|
|
11
|
+
) {
|
|
12
|
+
const { period = 'today' } = args as { period?: string };
|
|
13
|
+
|
|
14
|
+
// Validate period
|
|
15
|
+
if (!VALID_PERIODS.includes(period as UsageTimePeriod)) {
|
|
16
|
+
throw new Error(`Invalid period "${period}". Valid options: ${VALID_PERIODS.join(', ')}`);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
const stats = usageService.getStats(period as UsageTimePeriod);
|
|
20
|
+
|
|
21
|
+
// Format output
|
|
22
|
+
let output = `${duckArt.panel}\n\n`;
|
|
23
|
+
output += `š Usage Statistics: ${formatPeriodLabel(period as UsageTimePeriod)}\n`;
|
|
24
|
+
output += `āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā\n`;
|
|
25
|
+
output += `Period: ${stats.startDate} to ${stats.endDate}\n\n`;
|
|
26
|
+
|
|
27
|
+
// Totals section
|
|
28
|
+
output += `š TOTALS\n`;
|
|
29
|
+
output += `āāāāāāāāāāāāāāāāāāāāā\n`;
|
|
30
|
+
output += `Requests: ${stats.totals.requests.toLocaleString()}\n`;
|
|
31
|
+
output += `Prompt Tokens: ${stats.totals.promptTokens.toLocaleString()}\n`;
|
|
32
|
+
output += `Completion Tokens: ${stats.totals.completionTokens.toLocaleString()}\n`;
|
|
33
|
+
output += `Total Tokens: ${(stats.totals.promptTokens + stats.totals.completionTokens).toLocaleString()}\n`;
|
|
34
|
+
output += `Cache Hits: ${stats.totals.cacheHits.toLocaleString()}\n`;
|
|
35
|
+
output += `Errors: ${stats.totals.errors.toLocaleString()}\n`;
|
|
36
|
+
|
|
37
|
+
if (stats.totals.estimatedCostUSD !== undefined) {
|
|
38
|
+
output += `š° Estimated Cost: $${formatCost(stats.totals.estimatedCostUSD)} USD\n`;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// Per-provider breakdown
|
|
42
|
+
const providers = Object.keys(stats.usage);
|
|
43
|
+
if (providers.length > 0) {
|
|
44
|
+
output += `\nš¦ BY PROVIDER\n`;
|
|
45
|
+
output += `āāāāāāāāāāāāāāāāāāāāā\n`;
|
|
46
|
+
|
|
47
|
+
for (const provider of providers) {
|
|
48
|
+
const models = stats.usage[provider];
|
|
49
|
+
output += `\n**${provider}**\n`;
|
|
50
|
+
|
|
51
|
+
for (const [model, modelStats] of Object.entries(models)) {
|
|
52
|
+
output += ` ${model}:\n`;
|
|
53
|
+
output += ` Requests: ${modelStats.requests.toLocaleString()}\n`;
|
|
54
|
+
output += ` Tokens: ${modelStats.promptTokens.toLocaleString()} in / ${modelStats.completionTokens.toLocaleString()} out\n`;
|
|
55
|
+
if (modelStats.cacheHits > 0) {
|
|
56
|
+
output += ` Cache Hits: ${modelStats.cacheHits.toLocaleString()}\n`;
|
|
57
|
+
}
|
|
58
|
+
if (modelStats.errors > 0) {
|
|
59
|
+
output += ` Errors: ${modelStats.errors.toLocaleString()}\n`;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
if (stats.costByProvider && stats.costByProvider[provider] !== undefined) {
|
|
64
|
+
output += ` š° Provider Cost: $${formatCost(stats.costByProvider[provider])}\n`;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
} else {
|
|
68
|
+
output += `\nNo usage data for this period.\n`;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// Footer note about cost
|
|
72
|
+
if (stats.totals.estimatedCostUSD === undefined && stats.totals.requests > 0) {
|
|
73
|
+
output += `\nš” Cost estimates not available. Configure pricing in config.json or update to latest version.\n`;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
logger.info(`Retrieved usage stats for period: ${period}`);
|
|
77
|
+
|
|
78
|
+
return {
|
|
79
|
+
content: [
|
|
80
|
+
{
|
|
81
|
+
type: 'text',
|
|
82
|
+
text: output,
|
|
83
|
+
},
|
|
84
|
+
],
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function formatPeriodLabel(period: UsageTimePeriod): string {
|
|
89
|
+
switch (period) {
|
|
90
|
+
case 'today':
|
|
91
|
+
return 'Today';
|
|
92
|
+
case '7d':
|
|
93
|
+
return 'Last 7 Days';
|
|
94
|
+
case '30d':
|
|
95
|
+
return 'Last 30 Days';
|
|
96
|
+
case 'all':
|
|
97
|
+
return 'All Time';
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function formatCost(cost: number): string {
|
|
102
|
+
if (cost < 0.01) {
|
|
103
|
+
return cost.toFixed(6);
|
|
104
|
+
} else if (cost < 1) {
|
|
105
|
+
return cost.toFixed(4);
|
|
106
|
+
} else {
|
|
107
|
+
return cost.toFixed(2);
|
|
108
|
+
}
|
|
109
|
+
}
|