pi-usage-hub 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/.github/workflows/publish.yml +23 -0
- package/LICENSE +21 -0
- package/README.md +171 -0
- package/assets/usage-hub-footer.png +0 -0
- package/assets/usage-hub-panel.png +0 -0
- package/core/cache.ts +86 -0
- package/core/config.ts +152 -0
- package/core/registry.ts +73 -0
- package/examples/auth-providers.ts +42 -0
- package/index.ts +197 -0
- package/package.json +30 -0
- package/providers/ark.ts +154 -0
- package/providers/deepseek.ts +51 -0
- package/providers/kiro.ts +289 -0
- package/providers/newapi.ts +74 -0
- package/providers/opencode-go.ts +115 -0
- package/providers/xai.ts +311 -0
- package/session/collect.ts +275 -0
- package/types.ts +94 -0
- package/ui/format-report.ts +67 -0
- package/ui/format.ts +92 -0
- package/ui/session-panel.ts +178 -0
- package/ui/usage-window.ts +132 -0
- package/utils/chrome-cookies.ts +96 -0
- package/utils/duration.ts +17 -0
package/providers/xai.ts
ADDED
|
@@ -0,0 +1,311 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import type { UsageProvider, UsageReport, XaiConfig } from "../types";
|
|
5
|
+
import { agentDir } from "../core/config";
|
|
6
|
+
import { formatDurationMs } from "../utils/duration";
|
|
7
|
+
|
|
8
|
+
const PI_AUTH_PATH = () => join(agentDir(), "auth.json");
|
|
9
|
+
const GROK_AUTH_PATH = () => join(homedir(), ".grok", "auth.json");
|
|
10
|
+
const BILLING_BASE_URL = "https://cli-chat-proxy.grok.com/v1";
|
|
11
|
+
const XAI_OAUTH_CLIENT_ID = "b1a00492-073a-47ea-816f-4c329264a828";
|
|
12
|
+
const XAI_GROK_CLI_AUTH_SCOPE_KEY =
|
|
13
|
+
"https://auth.x.ai::b1a00492-073a-47ea-816f-4c329264a828";
|
|
14
|
+
const DEFAULT_TOKEN_ENDPOINT = "https://auth.x.ai/oauth2/token";
|
|
15
|
+
const FETCH_TIMEOUT_MS = 12_000;
|
|
16
|
+
const REFRESH_BUFFER_MS = 2 * 60 * 1000;
|
|
17
|
+
|
|
18
|
+
interface XaiCredentials {
|
|
19
|
+
access: string;
|
|
20
|
+
refresh?: string;
|
|
21
|
+
expires?: number;
|
|
22
|
+
tokenEndpoint?: string;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
interface MonthlyUsage {
|
|
26
|
+
monthlyLimit: number;
|
|
27
|
+
used: number;
|
|
28
|
+
billingPeriodEnd: string;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
interface WeeklyUsage {
|
|
32
|
+
creditUsagePercent: number;
|
|
33
|
+
billingPeriodEnd: string;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function readJson<T>(path: string): T | null {
|
|
37
|
+
try {
|
|
38
|
+
return JSON.parse(readFileSync(path, "utf-8")) as T;
|
|
39
|
+
} catch {
|
|
40
|
+
return null;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function parseExpiry(value: unknown): number | undefined {
|
|
45
|
+
if (typeof value === "number" && Number.isFinite(value)) return value;
|
|
46
|
+
if (typeof value !== "string" || !value.trim()) return undefined;
|
|
47
|
+
const numeric = Number(value);
|
|
48
|
+
if (Number.isFinite(numeric)) return numeric;
|
|
49
|
+
const parsed = Date.parse(value);
|
|
50
|
+
return Number.isFinite(parsed) ? parsed : undefined;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function readPiCredentials(): XaiCredentials | null {
|
|
54
|
+
const path = PI_AUTH_PATH();
|
|
55
|
+
if (!existsSync(path)) return null;
|
|
56
|
+
const auth = readJson<{ xai?: XaiCredentials; "xai-auth"?: XaiCredentials }>(path);
|
|
57
|
+
const entry = auth?.["xai-auth"] ?? auth?.xai;
|
|
58
|
+
if (!entry?.access) return null;
|
|
59
|
+
return {
|
|
60
|
+
access: String(entry.access),
|
|
61
|
+
refresh: entry.refresh ? String(entry.refresh) : undefined,
|
|
62
|
+
expires: parseExpiry(entry.expires),
|
|
63
|
+
tokenEndpoint: entry.tokenEndpoint ? String(entry.tokenEndpoint) : DEFAULT_TOKEN_ENDPOINT,
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function readGrokCliCredentials(): XaiCredentials | null {
|
|
68
|
+
const path = GROK_AUTH_PATH();
|
|
69
|
+
if (!existsSync(path)) return null;
|
|
70
|
+
const data = readJson<Record<string, any>>(path);
|
|
71
|
+
if (!data) return null;
|
|
72
|
+
|
|
73
|
+
const oidc = data[XAI_GROK_CLI_AUTH_SCOPE_KEY];
|
|
74
|
+
if (oidc && typeof oidc === "object") {
|
|
75
|
+
const access = String(oidc.key || oidc.access_token || oidc.token || "");
|
|
76
|
+
if (!access) return null;
|
|
77
|
+
return {
|
|
78
|
+
access,
|
|
79
|
+
refresh: oidc.refresh_token || oidc.refresh ? String(oidc.refresh_token || oidc.refresh) : undefined,
|
|
80
|
+
expires: parseExpiry(oidc.expires_at),
|
|
81
|
+
tokenEndpoint: DEFAULT_TOKEN_ENDPOINT,
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const topLevelAccess = data.access_token || data.token;
|
|
86
|
+
if (!topLevelAccess) return null;
|
|
87
|
+
return {
|
|
88
|
+
access: String(topLevelAccess),
|
|
89
|
+
refresh: data.refresh_token || data.refresh ? String(data.refresh_token || data.refresh) : undefined,
|
|
90
|
+
expires: parseExpiry(data.expires_at || data.expires),
|
|
91
|
+
tokenEndpoint: DEFAULT_TOKEN_ENDPOINT,
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function readStoredCredentials(): XaiCredentials | null {
|
|
96
|
+
return readPiCredentials() ?? readGrokCliCredentials();
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function isFresh(credentials: XaiCredentials): boolean {
|
|
100
|
+
if (!credentials.expires) return true;
|
|
101
|
+
return Date.now() < credentials.expires - REFRESH_BUFFER_MS;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function validateTokenEndpoint(url: string): string {
|
|
105
|
+
const parsed = new URL(url);
|
|
106
|
+
const host = parsed.hostname.toLowerCase();
|
|
107
|
+
if (parsed.protocol !== "https:" || (host !== "x.ai" && !host.endsWith(".x.ai"))) {
|
|
108
|
+
throw new Error(`unexpected xAI token endpoint: ${url}`);
|
|
109
|
+
}
|
|
110
|
+
return url;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
async function refreshCredentials(credentials: XaiCredentials): Promise<XaiCredentials> {
|
|
114
|
+
if (!credentials.refresh) {
|
|
115
|
+
throw new Error("session expired — run /login xai-auth");
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const tokenEndpoint = validateTokenEndpoint(credentials.tokenEndpoint || DEFAULT_TOKEN_ENDPOINT);
|
|
119
|
+
const body = new URLSearchParams({
|
|
120
|
+
grant_type: "refresh_token",
|
|
121
|
+
refresh_token: credentials.refresh,
|
|
122
|
+
client_id: XAI_OAUTH_CLIENT_ID,
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
const res = await fetch(tokenEndpoint, {
|
|
126
|
+
method: "POST",
|
|
127
|
+
headers: {
|
|
128
|
+
Accept: "application/json",
|
|
129
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
130
|
+
},
|
|
131
|
+
body,
|
|
132
|
+
});
|
|
133
|
+
|
|
134
|
+
if (!res.ok) throw new Error(`token refresh failed: HTTP ${res.status}`);
|
|
135
|
+
|
|
136
|
+
const data = await res.json() as {
|
|
137
|
+
access_token?: string;
|
|
138
|
+
refresh_token?: string;
|
|
139
|
+
expires_in?: number;
|
|
140
|
+
};
|
|
141
|
+
|
|
142
|
+
if (!data.access_token) throw new Error("token refresh failed: missing access token");
|
|
143
|
+
|
|
144
|
+
return {
|
|
145
|
+
access: data.access_token,
|
|
146
|
+
refresh: data.refresh_token || credentials.refresh,
|
|
147
|
+
expires: Date.now() + (data.expires_in ?? 3600) * 1000,
|
|
148
|
+
tokenEndpoint,
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function resetsInFromIso(iso: string | undefined): string | undefined {
|
|
153
|
+
if (!iso) return undefined;
|
|
154
|
+
const end = new Date(iso).getTime();
|
|
155
|
+
if (!Number.isFinite(end)) return undefined;
|
|
156
|
+
return formatDurationMs(end - Date.now());
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function parseMonthlyUsage(payload: unknown): MonthlyUsage {
|
|
160
|
+
if (!payload || typeof payload !== "object") throw new Error("invalid billing payload");
|
|
161
|
+
const config = (payload as Record<string, unknown>).config;
|
|
162
|
+
if (!config || typeof config !== "object") throw new Error("invalid billing payload");
|
|
163
|
+
|
|
164
|
+
const monthlyLimit = ((config as Record<string, unknown>).monthlyLimit as Record<string, unknown>)?.val;
|
|
165
|
+
const used = ((config as Record<string, unknown>).used as Record<string, unknown>)?.val;
|
|
166
|
+
const billingPeriodEnd = (config as Record<string, unknown>).billingPeriodEnd;
|
|
167
|
+
|
|
168
|
+
if (
|
|
169
|
+
typeof monthlyLimit !== "number" ||
|
|
170
|
+
!Number.isFinite(monthlyLimit) ||
|
|
171
|
+
typeof used !== "number" ||
|
|
172
|
+
!Number.isFinite(used) ||
|
|
173
|
+
typeof billingPeriodEnd !== "string" ||
|
|
174
|
+
!Number.isFinite(new Date(billingPeriodEnd).getTime())
|
|
175
|
+
) {
|
|
176
|
+
throw new Error("invalid billing payload");
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
return { monthlyLimit, used, billingPeriodEnd };
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function parseWeeklyUsage(payload: unknown): WeeklyUsage | undefined {
|
|
183
|
+
if (!payload || typeof payload !== "object") return undefined;
|
|
184
|
+
const config = (payload as Record<string, unknown>).config;
|
|
185
|
+
if (!config || typeof config !== "object") return undefined;
|
|
186
|
+
|
|
187
|
+
const currentPeriod = (config as Record<string, unknown>).currentPeriod as
|
|
188
|
+
| Record<string, unknown>
|
|
189
|
+
| undefined;
|
|
190
|
+
if (currentPeriod?.type !== "USAGE_PERIOD_TYPE_WEEKLY") return undefined;
|
|
191
|
+
|
|
192
|
+
const creditUsagePercent = (config as Record<string, unknown>).creditUsagePercent;
|
|
193
|
+
const billingPeriodEnd = (config as Record<string, unknown>).billingPeriodEnd;
|
|
194
|
+
if (
|
|
195
|
+
typeof creditUsagePercent !== "number" ||
|
|
196
|
+
!Number.isFinite(creditUsagePercent) ||
|
|
197
|
+
typeof billingPeriodEnd !== "string" ||
|
|
198
|
+
!Number.isFinite(new Date(billingPeriodEnd).getTime())
|
|
199
|
+
) {
|
|
200
|
+
return undefined;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
return { creditUsagePercent, billingPeriodEnd };
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
async function fetchJson(url: string, token: string): Promise<unknown> {
|
|
207
|
+
const controller = new AbortController();
|
|
208
|
+
const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
|
|
209
|
+
try {
|
|
210
|
+
const res = await fetch(url, {
|
|
211
|
+
headers: {
|
|
212
|
+
authorization: `Bearer ${token}`,
|
|
213
|
+
"x-xai-token-auth": "xai-grok-cli",
|
|
214
|
+
accept: "application/json",
|
|
215
|
+
"user-agent": "pi-usage-hub",
|
|
216
|
+
},
|
|
217
|
+
signal: controller.signal,
|
|
218
|
+
});
|
|
219
|
+
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
|
220
|
+
return await res.json();
|
|
221
|
+
} finally {
|
|
222
|
+
clearTimeout(timer);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
async function fetchBillingUsage(token: string): Promise<{ monthly: MonthlyUsage; weekly?: WeeklyUsage }> {
|
|
227
|
+
const monthly = parseMonthlyUsage(await fetchJson(`${BILLING_BASE_URL}/billing`, token));
|
|
228
|
+
let weekly: WeeklyUsage | undefined;
|
|
229
|
+
try {
|
|
230
|
+
const weeklyPayload = await fetchJson(`${BILLING_BASE_URL}/billing?format=credits`, token);
|
|
231
|
+
weekly = parseWeeklyUsage(weeklyPayload);
|
|
232
|
+
if (!weekly && weeklyPayload) {
|
|
233
|
+
const config = (weeklyPayload as any)?.config;
|
|
234
|
+
weekly = {
|
|
235
|
+
creditUsagePercent: 0,
|
|
236
|
+
billingPeriodEnd: config?.billingPeriodEnd || new Date().toISOString(),
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
} catch {
|
|
240
|
+
weekly = undefined;
|
|
241
|
+
}
|
|
242
|
+
return { monthly, weekly };
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
function mapUsage(monthly: MonthlyUsage, weekly?: WeeklyUsage): UsageReport {
|
|
246
|
+
const report: UsageReport = {};
|
|
247
|
+
|
|
248
|
+
if (weekly) {
|
|
249
|
+
report.weekly = {
|
|
250
|
+
pct: weekly.creditUsagePercent,
|
|
251
|
+
resetsIn: resetsInFromIso(weekly.billingPeriodEnd),
|
|
252
|
+
};
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
if (monthly.monthlyLimit > 0) {
|
|
256
|
+
report.monthly = {
|
|
257
|
+
pct: (monthly.used / monthly.monthlyLimit) * 100,
|
|
258
|
+
resetsIn: resetsInFromIso(monthly.billingPeriodEnd),
|
|
259
|
+
};
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
if (!report.weekly && !report.monthly) {
|
|
263
|
+
return { error: "could not parse usage" };
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
return report;
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
export function makeXaiProvider(name: string, cfg: XaiConfig = {}): UsageProvider {
|
|
270
|
+
let cachedCredentials: XaiCredentials | null = null;
|
|
271
|
+
|
|
272
|
+
async function getCredentials(): Promise<XaiCredentials | null> {
|
|
273
|
+
const stored = readStoredCredentials();
|
|
274
|
+
if (!stored) return null;
|
|
275
|
+
if (isFresh(stored)) {
|
|
276
|
+
cachedCredentials = stored;
|
|
277
|
+
return stored;
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
if (
|
|
281
|
+
cachedCredentials &&
|
|
282
|
+
cachedCredentials.refresh === stored.refresh &&
|
|
283
|
+
isFresh(cachedCredentials)
|
|
284
|
+
) {
|
|
285
|
+
return cachedCredentials;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
cachedCredentials = await refreshCredentials(stored);
|
|
289
|
+
return cachedCredentials;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
return {
|
|
293
|
+
key: name,
|
|
294
|
+
matchProviders: cfg.matchProviders ?? [name, "xai-auth", "xai", "grok-cli"],
|
|
295
|
+
shortLabel: cfg.shortLabel ?? "XAI",
|
|
296
|
+
label: cfg.label ?? "xAI (SuperGrok)",
|
|
297
|
+
detect: () => readStoredCredentials() !== null,
|
|
298
|
+
|
|
299
|
+
fetchUsage: async (): Promise<UsageReport> => {
|
|
300
|
+
try {
|
|
301
|
+
const credentials = await getCredentials();
|
|
302
|
+
if (!credentials) return { error: "not logged in — run /login xai-auth" };
|
|
303
|
+
const usage = await fetchBillingUsage(credentials.access);
|
|
304
|
+
return mapUsage(usage.monthly, usage.weekly);
|
|
305
|
+
} catch (err: any) {
|
|
306
|
+
if (err?.name === "AbortError") return { error: "timeout" };
|
|
307
|
+
return { error: err?.message ?? String(err) };
|
|
308
|
+
}
|
|
309
|
+
},
|
|
310
|
+
};
|
|
311
|
+
}
|
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
import { readdir, readFile } from "node:fs/promises";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
|
|
5
|
+
export interface TokenStats {
|
|
6
|
+
total: number;
|
|
7
|
+
input: number;
|
|
8
|
+
output: number;
|
|
9
|
+
cacheRead: number;
|
|
10
|
+
cacheWrite: number;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export interface SessionUsageTotals {
|
|
14
|
+
sessions: number;
|
|
15
|
+
messages: number;
|
|
16
|
+
cost: number;
|
|
17
|
+
tokens: TokenStats;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface ModelSessionUsage extends SessionUsageTotals {
|
|
21
|
+
model: string;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export interface ProviderSessionUsage extends SessionUsageTotals {
|
|
25
|
+
provider: string;
|
|
26
|
+
models: ModelSessionUsage[];
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface SessionUsagePeriod {
|
|
30
|
+
totals: SessionUsageTotals;
|
|
31
|
+
providers: ProviderSessionUsage[];
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface SessionUsageSummary {
|
|
35
|
+
today: SessionUsagePeriod;
|
|
36
|
+
thisWeek: SessionUsagePeriod;
|
|
37
|
+
thisMonth: SessionUsagePeriod;
|
|
38
|
+
allTime: SessionUsagePeriod;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
interface MutableStats {
|
|
42
|
+
sessions: Set<string>;
|
|
43
|
+
messages: number;
|
|
44
|
+
cost: number;
|
|
45
|
+
tokens: TokenStats;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
interface MutableProvider extends MutableStats {
|
|
49
|
+
models: Map<string, MutableStats>;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
interface MutablePeriod {
|
|
53
|
+
totals: MutableStats;
|
|
54
|
+
providers: Map<string, MutableProvider>;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
interface SessionMessage {
|
|
58
|
+
provider: string;
|
|
59
|
+
model: string;
|
|
60
|
+
cost: number;
|
|
61
|
+
input: number;
|
|
62
|
+
output: number;
|
|
63
|
+
cacheRead: number;
|
|
64
|
+
cacheWrite: number;
|
|
65
|
+
timestamp: number;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
type PeriodName = keyof SessionUsageSummary;
|
|
69
|
+
|
|
70
|
+
function getSessionsDir(): string {
|
|
71
|
+
const agentDir = process.env.PI_CODING_AGENT_DIR || join(homedir(), ".pi", "agent");
|
|
72
|
+
return join(agentDir, "sessions");
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
async function collectSessionFiles(dir: string, files: string[], signal?: AbortSignal): Promise<void> {
|
|
76
|
+
try {
|
|
77
|
+
const entries = await readdir(dir, { withFileTypes: true });
|
|
78
|
+
for (const entry of entries) {
|
|
79
|
+
if (signal?.aborted) return;
|
|
80
|
+
const entryPath = join(dir, entry.name);
|
|
81
|
+
if (entry.isDirectory()) {
|
|
82
|
+
await collectSessionFiles(entryPath, files, signal);
|
|
83
|
+
} else if (entry.isFile() && entry.name.endsWith(".jsonl")) {
|
|
84
|
+
files.push(entryPath);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
} catch {
|
|
88
|
+
// Ignore unreadable session directories.
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function emptyTokens(): TokenStats {
|
|
93
|
+
return { total: 0, input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function emptyStats(): MutableStats {
|
|
97
|
+
return { sessions: new Set(), messages: 0, cost: 0, tokens: emptyTokens() };
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function emptyProvider(): MutableProvider {
|
|
101
|
+
return { sessions: new Set(), messages: 0, cost: 0, tokens: emptyTokens(), models: new Map() };
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function emptyPeriod(): MutablePeriod {
|
|
105
|
+
return { totals: emptyStats(), providers: new Map() };
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function addStats(stats: MutableStats, sessionId: string, message: SessionMessage): void {
|
|
109
|
+
stats.sessions.add(sessionId);
|
|
110
|
+
stats.messages++;
|
|
111
|
+
stats.cost += message.cost;
|
|
112
|
+
stats.tokens.total += message.input + message.output + message.cacheWrite;
|
|
113
|
+
stats.tokens.input += message.input;
|
|
114
|
+
stats.tokens.output += message.output;
|
|
115
|
+
stats.tokens.cacheRead += message.cacheRead;
|
|
116
|
+
stats.tokens.cacheWrite += message.cacheWrite;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function periodsFor(timestamp: number, todayMs: number, weekStartMs: number, monthStartMs: number): PeriodName[] {
|
|
120
|
+
const periods: PeriodName[] = ["allTime"];
|
|
121
|
+
if (timestamp >= todayMs) periods.push("today");
|
|
122
|
+
if (timestamp >= weekStartMs) periods.push("thisWeek");
|
|
123
|
+
if (timestamp >= monthStartMs) periods.push("thisMonth");
|
|
124
|
+
return periods;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
async function parseSessionFile(
|
|
128
|
+
filePath: string,
|
|
129
|
+
seenHashes: Set<string>,
|
|
130
|
+
signal?: AbortSignal,
|
|
131
|
+
): Promise<{ sessionId: string; messages: SessionMessage[] } | null> {
|
|
132
|
+
try {
|
|
133
|
+
const content = await readFile(filePath, "utf8");
|
|
134
|
+
if (signal?.aborted) return null;
|
|
135
|
+
|
|
136
|
+
let sessionId = "";
|
|
137
|
+
const messages: SessionMessage[] = [];
|
|
138
|
+
const lines = content.trim().split("\n");
|
|
139
|
+
|
|
140
|
+
for (let i = 0; i < lines.length; i++) {
|
|
141
|
+
if (signal?.aborted) return null;
|
|
142
|
+
if (i % 500 === 0) await new Promise<void>(resolve => setImmediate(resolve));
|
|
143
|
+
|
|
144
|
+
const line = lines[i]?.trim();
|
|
145
|
+
if (!line) continue;
|
|
146
|
+
|
|
147
|
+
try {
|
|
148
|
+
const entry = JSON.parse(line);
|
|
149
|
+
if (entry.type === "session") {
|
|
150
|
+
sessionId = entry.id || sessionId;
|
|
151
|
+
continue;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
const msg = entry.type === "message" ? entry.message : null;
|
|
155
|
+
if (msg?.role !== "assistant" || !msg.usage || !msg.provider) continue;
|
|
156
|
+
|
|
157
|
+
const input = msg.usage.input || 0;
|
|
158
|
+
const output = msg.usage.output || 0;
|
|
159
|
+
const cacheRead = msg.usage.cacheRead || 0;
|
|
160
|
+
const cacheWrite = msg.usage.cacheWrite || 0;
|
|
161
|
+
const fallbackTs = entry.timestamp ? new Date(entry.timestamp).getTime() : 0;
|
|
162
|
+
const timestamp = msg.timestamp || (Number.isNaN(fallbackTs) ? 0 : fallbackTs);
|
|
163
|
+
const totalTokens = input + output + cacheRead + cacheWrite;
|
|
164
|
+
const hash = `${timestamp}:${totalTokens}`;
|
|
165
|
+
if (seenHashes.has(hash)) continue;
|
|
166
|
+
seenHashes.add(hash);
|
|
167
|
+
|
|
168
|
+
messages.push({
|
|
169
|
+
provider: msg.provider,
|
|
170
|
+
model: msg.model || "unknown",
|
|
171
|
+
cost: msg.usage.cost?.total || 0,
|
|
172
|
+
input,
|
|
173
|
+
output,
|
|
174
|
+
cacheRead,
|
|
175
|
+
cacheWrite,
|
|
176
|
+
timestamp,
|
|
177
|
+
});
|
|
178
|
+
} catch {
|
|
179
|
+
// Skip malformed entries.
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
return sessionId ? { sessionId, messages } : null;
|
|
184
|
+
} catch {
|
|
185
|
+
return null;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function finalizeStats(stats: MutableStats): SessionUsageTotals {
|
|
190
|
+
return {
|
|
191
|
+
sessions: stats.sessions.size,
|
|
192
|
+
messages: stats.messages,
|
|
193
|
+
cost: stats.cost,
|
|
194
|
+
tokens: stats.tokens,
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function finalizePeriod(period: MutablePeriod): SessionUsagePeriod {
|
|
199
|
+
const providers = Array.from(period.providers.entries())
|
|
200
|
+
.map(([provider, stats]) => ({
|
|
201
|
+
provider,
|
|
202
|
+
...finalizeStats(stats),
|
|
203
|
+
models: Array.from(stats.models.entries())
|
|
204
|
+
.map(([model, m]) => ({ model, ...finalizeStats(m) }))
|
|
205
|
+
.sort((a, b) => b.cost - a.cost || b.tokens.total - a.tokens.total),
|
|
206
|
+
}))
|
|
207
|
+
.sort((a, b) => b.cost - a.cost || b.tokens.total - a.tokens.total);
|
|
208
|
+
|
|
209
|
+
return {
|
|
210
|
+
totals: finalizeStats(period.totals),
|
|
211
|
+
providers,
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
export async function collectSessionUsage(signal?: AbortSignal): Promise<SessionUsageSummary> {
|
|
216
|
+
const startOfToday = new Date();
|
|
217
|
+
startOfToday.setHours(0, 0, 0, 0);
|
|
218
|
+
const todayMs = startOfToday.getTime();
|
|
219
|
+
|
|
220
|
+
const startOfWeek = new Date();
|
|
221
|
+
const dayOfWeek = startOfWeek.getDay();
|
|
222
|
+
const daysSinceMonday = dayOfWeek === 0 ? 6 : dayOfWeek - 1;
|
|
223
|
+
startOfWeek.setDate(startOfWeek.getDate() - daysSinceMonday);
|
|
224
|
+
startOfWeek.setHours(0, 0, 0, 0);
|
|
225
|
+
const weekStartMs = startOfWeek.getTime();
|
|
226
|
+
|
|
227
|
+
const startOfMonth = new Date();
|
|
228
|
+
startOfMonth.setDate(1);
|
|
229
|
+
startOfMonth.setHours(0, 0, 0, 0);
|
|
230
|
+
const monthStartMs = startOfMonth.getTime();
|
|
231
|
+
|
|
232
|
+
const periods: Record<PeriodName, MutablePeriod> = {
|
|
233
|
+
today: emptyPeriod(),
|
|
234
|
+
thisWeek: emptyPeriod(),
|
|
235
|
+
thisMonth: emptyPeriod(),
|
|
236
|
+
allTime: emptyPeriod(),
|
|
237
|
+
};
|
|
238
|
+
|
|
239
|
+
const files: string[] = [];
|
|
240
|
+
await collectSessionFiles(getSessionsDir(), files, signal);
|
|
241
|
+
files.sort();
|
|
242
|
+
|
|
243
|
+
const seenHashes = new Set<string>();
|
|
244
|
+
for (const file of files) {
|
|
245
|
+
if (signal?.aborted) break;
|
|
246
|
+
const parsed = await parseSessionFile(file, seenHashes, signal);
|
|
247
|
+
if (!parsed) continue;
|
|
248
|
+
|
|
249
|
+
for (const message of parsed.messages) {
|
|
250
|
+
for (const periodName of periodsFor(message.timestamp, todayMs, weekStartMs, monthStartMs)) {
|
|
251
|
+
const period = periods[periodName];
|
|
252
|
+
let provider = period.providers.get(message.provider);
|
|
253
|
+
if (!provider) {
|
|
254
|
+
provider = emptyProvider();
|
|
255
|
+
period.providers.set(message.provider, provider);
|
|
256
|
+
}
|
|
257
|
+
let model = provider.models.get(message.model);
|
|
258
|
+
if (!model) {
|
|
259
|
+
model = emptyStats();
|
|
260
|
+
provider.models.set(message.model, model);
|
|
261
|
+
}
|
|
262
|
+
addStats(model, parsed.sessionId, message);
|
|
263
|
+
addStats(provider, parsed.sessionId, message);
|
|
264
|
+
addStats(period.totals, parsed.sessionId, message);
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
return {
|
|
270
|
+
today: finalizePeriod(periods.today),
|
|
271
|
+
thisWeek: finalizePeriod(periods.thisWeek),
|
|
272
|
+
thisMonth: finalizePeriod(periods.thisMonth),
|
|
273
|
+
allTime: finalizePeriod(periods.allTime),
|
|
274
|
+
};
|
|
275
|
+
}
|
package/types.ts
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
export interface UsageData {
|
|
2
|
+
pct: number;
|
|
3
|
+
resetsIn?: string;
|
|
4
|
+
}
|
|
5
|
+
|
|
6
|
+
export interface UsageReport {
|
|
7
|
+
session?: UsageData;
|
|
8
|
+
weekly?: UsageData;
|
|
9
|
+
monthly?: UsageData;
|
|
10
|
+
error?: string;
|
|
11
|
+
displayText?: string;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface UsageProvider {
|
|
15
|
+
key: string;
|
|
16
|
+
/** model.provider values this usage entry matches (besides key). */
|
|
17
|
+
matchProviders?: string[];
|
|
18
|
+
shortLabel: string;
|
|
19
|
+
label: string;
|
|
20
|
+
detect(): boolean;
|
|
21
|
+
fetchUsage(): Promise<UsageReport>;
|
|
22
|
+
login?(): Promise<boolean>;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Built-in factory id (L1 `type` field). */
|
|
26
|
+
export type ProviderType =
|
|
27
|
+
| "deepseek"
|
|
28
|
+
| "newapi"
|
|
29
|
+
| "ark"
|
|
30
|
+
| "opencode-go"
|
|
31
|
+
| "xai"
|
|
32
|
+
| "kiro";
|
|
33
|
+
|
|
34
|
+
/** Shared optional fields for factories and config entries. */
|
|
35
|
+
export interface ProviderMeta {
|
|
36
|
+
matchProviders?: string[];
|
|
37
|
+
shortLabel?: string;
|
|
38
|
+
label?: string;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Factory input — no type (caller already picked the factory). */
|
|
42
|
+
export interface DeepseekConfig extends ProviderMeta {
|
|
43
|
+
apiKey: string;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export interface NewApiConfig extends ProviderMeta {
|
|
47
|
+
host: string;
|
|
48
|
+
token: string;
|
|
49
|
+
userId: string;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export interface ArkConfig extends ProviderMeta {
|
|
53
|
+
/** Full Cookie header; if set, skips Chrome. */
|
|
54
|
+
cookie?: string;
|
|
55
|
+
/** Optional CSRF; otherwise parsed from cookie (`csrfToken=`). */
|
|
56
|
+
csrfToken?: string;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export interface OpencodeGoConfig extends ProviderMeta {
|
|
60
|
+
workspaceId: string;
|
|
61
|
+
/** `auth` cookie value; if set, skips Chrome. */
|
|
62
|
+
auth?: string;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export interface XaiConfig extends ProviderMeta {}
|
|
66
|
+
|
|
67
|
+
export interface KiroConfig extends ProviderMeta {}
|
|
68
|
+
|
|
69
|
+
/** L1 entry after parse — name always set (auto: type, type-2, … when omitted/clashing). */
|
|
70
|
+
export type ProviderConfig =
|
|
71
|
+
| ({ name: string; type: "deepseek" } & DeepseekConfig)
|
|
72
|
+
| ({ name: string; type: "newapi" } & NewApiConfig)
|
|
73
|
+
| ({ name: string; type: "ark" } & ArkConfig)
|
|
74
|
+
| ({ name: string; type: "opencode-go" } & OpencodeGoConfig)
|
|
75
|
+
| ({ name: string; type: "xai" } & XaiConfig)
|
|
76
|
+
| ({ name: string; type: "kiro" } & KiroConfig);
|
|
77
|
+
|
|
78
|
+
export interface UsageHubConfig {
|
|
79
|
+
providers?: ProviderConfig[];
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export interface UsageHub {
|
|
83
|
+
register(p: UsageProvider): void;
|
|
84
|
+
unregister(key: string): void;
|
|
85
|
+
list(): UsageProvider[];
|
|
86
|
+
/** Match model → cached one-line summary, or null if no provider / not fetched yet. */
|
|
87
|
+
getSummary(model?: { provider?: string }): string | null;
|
|
88
|
+
getReport(key: string): UsageReport | null;
|
|
89
|
+
refresh(opts?: {
|
|
90
|
+
model?: { provider?: string };
|
|
91
|
+
force?: boolean;
|
|
92
|
+
}): Promise<string | null>;
|
|
93
|
+
invalidate(key?: string): void;
|
|
94
|
+
}
|