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.
@@ -0,0 +1,289 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import type { KiroConfig, UsageProvider, UsageReport } from "../types";
4
+ import { agentDir } from "../core/config";
5
+ import { formatDurationSeconds } from "../utils/duration";
6
+
7
+ const PI_AUTH_PATH = () => join(agentDir(), "auth.json");
8
+ const FETCH_TIMEOUT_MS = 12_000;
9
+ const REFRESH_BUFFER_MS = 2 * 60 * 1000;
10
+ const KIRO_DESKTOP_REFRESH_URL = "https://prod.{region}.auth.desktop.kiro.dev/refreshToken";
11
+
12
+ interface KiroCredentials {
13
+ accessToken: string;
14
+ expiresAt: number;
15
+ region: string;
16
+ profileArn?: string;
17
+ refresh?: string;
18
+ authMethod?: string;
19
+ clientId?: string;
20
+ clientSecret?: string;
21
+ }
22
+
23
+ interface PiKiroAuthEntry {
24
+ type?: string;
25
+ refresh?: string;
26
+ access?: string;
27
+ expires?: number;
28
+ clientId?: string;
29
+ clientSecret?: string;
30
+ region?: string;
31
+ authMethod?: string;
32
+ profileArn?: string;
33
+ }
34
+
35
+ interface KiroUsageBreakdown {
36
+ currentUsage?: number;
37
+ currentUsageWithPrecision?: number;
38
+ usageLimit?: number;
39
+ usageLimitWithPrecision?: number;
40
+ nextDateReset?: string | number;
41
+ }
42
+
43
+ interface KiroUsageResponse {
44
+ nextDateReset?: string | number;
45
+ usageBreakdown?: KiroUsageBreakdown;
46
+ usageBreakdownList?: KiroUsageBreakdown[];
47
+ }
48
+
49
+ interface KiroListProfilesResponse {
50
+ profiles?: Array<{ arn?: string }>;
51
+ }
52
+
53
+ function readJson<T>(path: string): T | null {
54
+ try {
55
+ return JSON.parse(readFileSync(path, "utf-8")) as T;
56
+ } catch {
57
+ return null;
58
+ }
59
+ }
60
+
61
+ function readTokenCredentials(): KiroCredentials | null {
62
+ const path = PI_AUTH_PATH();
63
+ if (!existsSync(path)) return null;
64
+
65
+ const auth = readJson<{ kiro?: PiKiroAuthEntry }>(path);
66
+ const tokenData = auth?.kiro;
67
+ if (tokenData?.type !== "oauth" || !tokenData.access || !tokenData.expires) return null;
68
+
69
+ const expiresAt = tokenData.expires;
70
+ if (!Number.isFinite(expiresAt)) return null;
71
+
72
+ return {
73
+ accessToken: tokenData.access,
74
+ expiresAt,
75
+ region: tokenData.region ?? "us-east-1",
76
+ profileArn: tokenData.profileArn,
77
+ refresh: tokenData.refresh,
78
+ authMethod: tokenData.authMethod,
79
+ clientId: tokenData.clientId,
80
+ clientSecret: tokenData.clientSecret,
81
+ };
82
+ }
83
+
84
+ function isFresh(credentials: KiroCredentials): boolean {
85
+ return Date.now() < credentials.expiresAt - REFRESH_BUFFER_MS;
86
+ }
87
+
88
+ async function refreshCredentials(credentials: KiroCredentials): Promise<KiroCredentials> {
89
+ if (!credentials.refresh) {
90
+ throw new Error("session expired — run /login kiro to refresh");
91
+ }
92
+
93
+ const parts = credentials.refresh.split("|");
94
+ const refreshToken = parts[0] ?? "";
95
+ const authMethod = credentials.authMethod ?? parts[parts.length - 1] ?? "idc";
96
+ const region = credentials.region || "us-east-1";
97
+ if (!refreshToken) throw new Error("session expired — run /login kiro to refresh");
98
+
99
+ if (authMethod === "desktop") {
100
+ const res = await fetch(KIRO_DESKTOP_REFRESH_URL.replace("{region}", region), {
101
+ method: "POST",
102
+ headers: { "content-type": "application/json", "user-agent": "pi-usage-hub" },
103
+ body: JSON.stringify({ refreshToken }),
104
+ });
105
+ if (!res.ok) throw new Error(`token refresh failed: HTTP ${res.status}`);
106
+
107
+ const data = await res.json() as {
108
+ accessToken?: string;
109
+ refreshToken?: string;
110
+ expiresIn?: number;
111
+ profileArn?: string;
112
+ };
113
+ if (!data.accessToken) throw new Error("token refresh failed: missing access token");
114
+
115
+ return {
116
+ ...credentials,
117
+ accessToken: data.accessToken,
118
+ refresh: `${data.refreshToken || refreshToken}|desktop`,
119
+ expiresAt: Date.now() + (data.expiresIn ?? 3600) * 1000,
120
+ region,
121
+ authMethod: "desktop",
122
+ profileArn: data.profileArn || credentials.profileArn,
123
+ };
124
+ }
125
+
126
+ const clientId = credentials.clientId ?? parts[1] ?? "";
127
+ const clientSecret = credentials.clientSecret ?? parts[2] ?? "";
128
+ if (!clientId || !clientSecret) {
129
+ throw new Error("session expired — run /login kiro to refresh");
130
+ }
131
+
132
+ const res = await fetch(`https://oidc.${region}.amazonaws.com/token`, {
133
+ method: "POST",
134
+ headers: { "content-type": "application/json", "user-agent": "pi-usage-hub" },
135
+ body: JSON.stringify({ clientId, clientSecret, refreshToken, grantType: "refresh_token" }),
136
+ });
137
+ if (!res.ok) throw new Error(`token refresh failed: HTTP ${res.status}`);
138
+
139
+ const data = await res.json() as { accessToken?: string; refreshToken?: string; expiresIn?: number };
140
+ if (!data.accessToken) throw new Error("token refresh failed: missing access token");
141
+
142
+ return {
143
+ ...credentials,
144
+ accessToken: data.accessToken,
145
+ refresh: `${data.refreshToken || refreshToken}|${clientId}|${clientSecret}|idc`,
146
+ expiresAt: Date.now() + (data.expiresIn ?? 3600) * 1000,
147
+ region,
148
+ authMethod: "idc",
149
+ clientId,
150
+ clientSecret,
151
+ };
152
+ }
153
+
154
+ function parseReset(value: string | number | undefined): number | undefined {
155
+ if (value == null) return undefined;
156
+ if (typeof value === "number") return value > 10_000_000_000 ? value / 1000 : value;
157
+ const ms = new Date(value).getTime();
158
+ return Number.isFinite(ms) ? ms / 1000 : undefined;
159
+ }
160
+
161
+ async function postKiro<T>(credentials: KiroCredentials, target: string, body: Record<string, unknown>): Promise<T> {
162
+ const controller = new AbortController();
163
+ const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
164
+
165
+ try {
166
+ const res = await fetch(`https://q.${credentials.region}.amazonaws.com/`, {
167
+ method: "POST",
168
+ headers: {
169
+ authorization: `Bearer ${credentials.accessToken}`,
170
+ "content-type": "application/x-amz-json-1.0",
171
+ "x-amz-target": target,
172
+ "user-agent": "pi-usage-hub",
173
+ },
174
+ body: JSON.stringify(body),
175
+ signal: controller.signal,
176
+ });
177
+
178
+ if (!res.ok) {
179
+ const text = await res.text();
180
+ throw new Error(`HTTP ${res.status}${text ? ` ${text}` : ""}`);
181
+ }
182
+
183
+ return await res.json() as T;
184
+ } finally {
185
+ clearTimeout(timer);
186
+ }
187
+ }
188
+
189
+ async function resolveProfileArn(credentials: KiroCredentials): Promise<string | undefined> {
190
+ if (credentials.profileArn) return credentials.profileArn;
191
+
192
+ try {
193
+ const data = await postKiro<KiroListProfilesResponse>(
194
+ credentials,
195
+ "AmazonCodeWhispererService.ListAvailableProfiles",
196
+ {},
197
+ );
198
+ return data.profiles?.find(profile => profile.arn)?.arn;
199
+ } catch {
200
+ return undefined;
201
+ }
202
+ }
203
+
204
+ function usageBodies(profileArn: string | undefined): Array<Record<string, unknown>> {
205
+ const maybeProfile = profileArn ? { profileArn } : {};
206
+ return [
207
+ { ...maybeProfile, origin: "AI_EDITOR", resourceType: "AGENTIC_REQUEST", isEmailRequired: true },
208
+ { ...maybeProfile, origin: "AI_EDITOR", resourceType: "AGENTIC_REQUEST" },
209
+ { ...maybeProfile, origin: "CLI", resourceType: "CREDIT", isEmailRequired: false },
210
+ { ...maybeProfile, origin: "CLI", resourceType: "CREDIT" },
211
+ { ...maybeProfile, origin: "CLI" },
212
+ maybeProfile,
213
+ ];
214
+ }
215
+
216
+ async function fetchUsageData(credentials: KiroCredentials): Promise<KiroUsageResponse> {
217
+ const profileArn = await resolveProfileArn(credentials);
218
+ const errors: string[] = [];
219
+
220
+ for (const body of usageBodies(profileArn)) {
221
+ try {
222
+ return await postKiro<KiroUsageResponse>(
223
+ credentials,
224
+ "AmazonCodeWhispererService.GetUsageLimits",
225
+ body,
226
+ );
227
+ } catch (err: any) {
228
+ errors.push(err?.message ?? String(err));
229
+ }
230
+ }
231
+
232
+ throw new Error(errors[0] ?? "usage fetch failed");
233
+ }
234
+
235
+ function mapUsage(data: KiroUsageResponse): UsageReport {
236
+ const item = data.usageBreakdownList?.[0] ?? data.usageBreakdown;
237
+ if (!item) return { error: "could not parse usage" };
238
+
239
+ const used = item.currentUsageWithPrecision ?? item.currentUsage ?? 0;
240
+ const limit = item.usageLimitWithPrecision ?? item.usageLimit ?? 0;
241
+ if (!limit) return { error: "no usage limit" };
242
+
243
+ const pct = (used / limit) * 100;
244
+ const resetTs = parseReset(item.nextDateReset ?? data.nextDateReset);
245
+ const resetsIn = resetTs ? formatDurationSeconds(resetTs - Date.now() / 1000) : "";
246
+
247
+ return { session: { pct, resetsIn } };
248
+ }
249
+
250
+ export function makeKiroProvider(name: string, cfg: KiroConfig = {}): UsageProvider {
251
+ let cachedRefreshCredentials: KiroCredentials | null = null;
252
+
253
+ async function getCredentials(): Promise<KiroCredentials | null> {
254
+ const credentials = readTokenCredentials();
255
+ if (!credentials) return null;
256
+ if (isFresh(credentials)) return credentials;
257
+
258
+ if (
259
+ cachedRefreshCredentials &&
260
+ cachedRefreshCredentials.refresh === credentials.refresh &&
261
+ isFresh(cachedRefreshCredentials)
262
+ ) {
263
+ return cachedRefreshCredentials;
264
+ }
265
+
266
+ cachedRefreshCredentials = await refreshCredentials(credentials);
267
+ return cachedRefreshCredentials;
268
+ }
269
+
270
+ return {
271
+ key: name,
272
+ matchProviders: cfg.matchProviders ?? [name, "kiro"],
273
+ shortLabel: cfg.shortLabel ?? "KIRO",
274
+ label: cfg.label ?? "Kiro",
275
+ // Presence in config enables the provider; auth comes from auth.json.
276
+ detect: () => true,
277
+
278
+ fetchUsage: async (): Promise<UsageReport> => {
279
+ try {
280
+ const credentials = await getCredentials();
281
+ if (!credentials) return { error: "not logged in — run /login kiro" };
282
+ return mapUsage(await fetchUsageData(credentials));
283
+ } catch (err: any) {
284
+ if (err?.name === "AbortError") return { error: "timeout" };
285
+ return { error: err?.message ?? String(err) };
286
+ }
287
+ },
288
+ };
289
+ }
@@ -0,0 +1,74 @@
1
+ import type { NewApiConfig, UsageProvider, UsageReport } from "../types";
2
+
3
+ const QUOTA_PER_DOLLAR = 500_000;
4
+ const FETCH_TIMEOUT_MS = 10_000;
5
+ const BJ_OFFSET_MS = 8 * 60 * 60 * 1000;
6
+
7
+ async function apiGet(cfg: NewApiConfig, endpoint: string): Promise<any> {
8
+ const controller = new AbortController();
9
+ const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
10
+ try {
11
+ const res = await fetch(`${cfg.host}${endpoint}`, {
12
+ headers: {
13
+ "Content-Type": "application/json",
14
+ Authorization: `Bearer ${cfg.token}`,
15
+ "New-Api-User": cfg.userId,
16
+ },
17
+ signal: controller.signal,
18
+ });
19
+ if (!res.ok) return null;
20
+ return await res.json();
21
+ } catch {
22
+ return null;
23
+ } finally {
24
+ clearTimeout(timer);
25
+ }
26
+ }
27
+
28
+ async function fetchBalance(cfg: NewApiConfig): Promise<number | null> {
29
+ const data = await apiGet(cfg, "/api/user/self");
30
+ if (!data?.success || !data?.data) return null;
31
+ return (data.data.quota ?? 0) / QUOTA_PER_DOLLAR;
32
+ }
33
+
34
+ async function fetchTodayUsage(cfg: NewApiConfig): Promise<number | null> {
35
+ const nowMs = Date.now();
36
+ const startMs = Math.floor((nowMs + BJ_OFFSET_MS) / 86_400_000) * 86_400_000 - BJ_OFFSET_MS;
37
+ const startTs = Math.floor(startMs / 1000);
38
+ const endTs = Math.floor(nowMs / 1000);
39
+ const data = await apiGet(
40
+ cfg,
41
+ `/api/data/self?start_timestamp=${startTs}&end_timestamp=${endTs}&default_time=day`,
42
+ );
43
+ if (!data?.success) return null;
44
+ const rows: any[] = data.data ?? [];
45
+ return rows.reduce((sum: number, r: any) => sum + (r.quota ?? 0), 0) / QUOTA_PER_DOLLAR;
46
+ }
47
+
48
+ function fmt(v: number | null): string {
49
+ return v === null ? "$?" : `$${v.toFixed(2)}`;
50
+ }
51
+
52
+ function labelFromName(name: string): string {
53
+ return name.replace(/[-_]+/g, "-").toUpperCase();
54
+ }
55
+
56
+ export function makeNewApiProvider(name: string, cfg: NewApiConfig): UsageProvider {
57
+ const shortLabel = cfg.shortLabel ?? labelFromName(name);
58
+ return {
59
+ key: name,
60
+ matchProviders: cfg.matchProviders ?? [name],
61
+ shortLabel,
62
+ label: cfg.label ?? `NewAPI ${shortLabel}`,
63
+ detect: () => !!(cfg.host && cfg.token && cfg.userId),
64
+
65
+ fetchUsage: async (): Promise<UsageReport> => {
66
+ if (!cfg.host || !cfg.token || !cfg.userId) {
67
+ return { error: `no credentials — add ${name} to pi-usage-hub.json` };
68
+ }
69
+ const [balance, today] = await Promise.all([fetchBalance(cfg), fetchTodayUsage(cfg)]);
70
+ if (balance === null) return { error: "failed to fetch balance" };
71
+ return { displayText: `${fmt(balance)} · ${fmt(today)}` };
72
+ },
73
+ };
74
+ }
@@ -0,0 +1,115 @@
1
+ import { execFile } from "node:child_process";
2
+ import type { OpencodeGoConfig, UsageProvider, UsageReport } from "../types";
3
+ import { readChromeCookies } from "../utils/chrome-cookies";
4
+ import { formatDurationSeconds } from "../utils/duration";
5
+
6
+ const SCRAPED_NUMBER = "(-?\\d+(?:\\.\\d+)?)";
7
+ const FETCH_TIMEOUT_MS = 10_000;
8
+
9
+ function makeRe(key: string): RegExp[] {
10
+ const pctFirst = new RegExp(`${key}:\\$R\\[\\d+\\]=\\{[^}]*usagePercent:${SCRAPED_NUMBER}[^}]*resetInSec:${SCRAPED_NUMBER}[^}]*\\}`);
11
+ const resetFirst = new RegExp(`${key}:\\$R\\[\\d+\\]=\\{[^}]*resetInSec:${SCRAPED_NUMBER}[^}]*usagePercent:${SCRAPED_NUMBER}[^}]*\\}`);
12
+ return [pctFirst, resetFirst];
13
+ }
14
+
15
+ function parseWindow(html: string, key: string): { pct: number; resetsInSec: number } | null {
16
+ const [rePct, reReset] = makeRe(key);
17
+ const m1 = rePct.exec(html);
18
+ if (m1) {
19
+ const pct = Number(m1[1]), sec = Number(m1[2]);
20
+ if (Number.isFinite(pct) && Number.isFinite(sec)) return { pct, resetsInSec: sec };
21
+ }
22
+ const m2 = reReset.exec(html);
23
+ if (m2) {
24
+ const sec = Number(m2[1]), pct = Number(m2[2]);
25
+ if (Number.isFinite(pct) && Number.isFinite(sec)) return { pct, resetsInSec: sec };
26
+ }
27
+ return null;
28
+ }
29
+
30
+ function readChromeAuthCookie(): string | null {
31
+ if (process.platform !== "darwin") return null;
32
+ const cookies = readChromeCookies("%opencode.ai%", ["opencode.ai", ".opencode.ai"]);
33
+ return cookies.find(c => c.name === "auth")?.value ?? null;
34
+ }
35
+
36
+ function resolveAuth(cfg: OpencodeGoConfig): string | null {
37
+ if (cfg.auth?.trim()) return cfg.auth.trim();
38
+ return readChromeAuthCookie();
39
+ }
40
+
41
+ export function makeOpencodeGoProvider(name: string, cfg: OpencodeGoConfig): UsageProvider {
42
+ const workspaceId = cfg.workspaceId;
43
+ const manual = !!cfg.auth?.trim();
44
+
45
+ return {
46
+ key: name,
47
+ matchProviders: cfg.matchProviders ?? [name, "opencode-go"],
48
+ shortLabel: cfg.shortLabel ?? "OCG",
49
+ label: cfg.label ?? "OpenCode Go",
50
+ detect: () => !!workspaceId && (!!resolveAuth(cfg) || !manual),
51
+
52
+ fetchUsage: async (): Promise<UsageReport> => {
53
+ if (!workspaceId) return { error: "no credentials configured" };
54
+
55
+ const authCookie = resolveAuth(cfg);
56
+ if (!authCookie) {
57
+ return {
58
+ error: manual
59
+ ? "invalid auth in config"
60
+ : "not logged in — set auth in config or /usage-hub login ocg",
61
+ };
62
+ }
63
+
64
+ const controller = new AbortController();
65
+ const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
66
+
67
+ try {
68
+ const res = await fetch(
69
+ `https://opencode.ai/workspace/${encodeURIComponent(workspaceId)}/go`,
70
+ {
71
+ headers: {
72
+ "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) Gecko/20100101 Firefox/148.0",
73
+ Accept: "text/html",
74
+ Cookie: `auth=${authCookie}`,
75
+ },
76
+ signal: controller.signal,
77
+ },
78
+ );
79
+
80
+ if (!res.ok) return { error: `HTTP ${res.status}` };
81
+
82
+ const html = await res.text();
83
+ const rolling = parseWindow(html, "rollingUsage");
84
+ const weekly = parseWindow(html, "weeklyUsage");
85
+ const monthly = parseWindow(html, "monthlyUsage");
86
+
87
+ if (!rolling && !weekly && !monthly) return { error: "could not parse usage from dashboard" };
88
+
89
+ const report: UsageReport = {};
90
+ if (rolling) report.session = { pct: rolling.pct, resetsIn: formatDurationSeconds(rolling.resetsInSec) };
91
+ if (weekly) report.weekly = { pct: weekly.pct, resetsIn: formatDurationSeconds(weekly.resetsInSec) };
92
+ if (monthly) report.monthly = { pct: monthly.pct, resetsIn: formatDurationSeconds(monthly.resetsInSec) };
93
+ return report;
94
+ } catch (err: any) {
95
+ if (err?.name === "AbortError") return { error: "timeout" };
96
+ return { error: err?.message ?? String(err) };
97
+ } finally {
98
+ clearTimeout(timer);
99
+ }
100
+ },
101
+
102
+ login: manual
103
+ ? undefined
104
+ : async (): Promise<boolean> => {
105
+ if (!workspaceId) return false;
106
+ execFile("open", ["-a", "Google Chrome", `https://opencode.ai/workspace/${workspaceId}/go`]);
107
+ const deadline = Date.now() + 300_000;
108
+ while (Date.now() < deadline) {
109
+ await new Promise(r => setTimeout(r, 2000));
110
+ if (readChromeAuthCookie()) return true;
111
+ }
112
+ return false;
113
+ },
114
+ };
115
+ }