@fenlyin/pi-subscription-usage 0.0.0-stage → 2.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 +24 -0
- package/README.md +157 -3
- package/README.zh-CN.md +157 -0
- package/THIRD_PARTY_NOTICES.md +28 -0
- package/index.ts +1 -0
- package/package.json +52 -6
- package/src/codex-reset-core.ts +249 -0
- package/src/codex-resets.ts +145 -0
- package/src/config-core.ts +43 -0
- package/src/config.ts +48 -0
- package/src/core.ts +182 -0
- package/src/display.ts +55 -0
- package/src/format.ts +225 -0
- package/src/providers/claude-bridge.ts +118 -0
- package/src/providers/codex-constants.ts +2 -0
- package/src/providers/codex.ts +227 -0
- package/src/providers/grok.ts +358 -0
- package/src/providers/kimi.ts +155 -0
- package/src/providers/openai.ts +145 -0
- package/src/providers/opencode-go.ts +88 -0
- package/src/query.ts +511 -0
- package/src/status.ts +291 -0
- package/src/types.ts +90 -0
- package/src/usage.ts +710 -0
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
// pi-claude-bridge has no usage endpoint Pi can call: Claude Code reports plan
|
|
2
|
+
// usage as rate_limit_event messages, which the bridge replays to Pi as
|
|
3
|
+
// `anthropic-ratelimit-unified-*` headers on after_provider_response.
|
|
4
|
+
// This module turns those headers into a report; nothing here sends a request.
|
|
5
|
+
import type { UsageBucket, UsageReport } from "../types.ts";
|
|
6
|
+
|
|
7
|
+
export const CLAUDE_BRIDGE_PROVIDER_ID = "claude-bridge";
|
|
8
|
+
|
|
9
|
+
const HEADER_PREFIX = "anthropic-ratelimit-unified-";
|
|
10
|
+
// Observed: utilization is a 0..1 fraction. Anything far above 1 means the
|
|
11
|
+
// scale changed, and a guessed percentage would be worse than none.
|
|
12
|
+
const MAX_UTILIZATION = 1.5;
|
|
13
|
+
// Unix seconds; a millisecond value would land past this bound.
|
|
14
|
+
const MAX_EPOCH_SECONDS = 10_000_000_000;
|
|
15
|
+
|
|
16
|
+
const CLAUDE_WINDOWS: readonly {
|
|
17
|
+
abbreviation: string;
|
|
18
|
+
id: string;
|
|
19
|
+
label: string;
|
|
20
|
+
windowMinutes: number;
|
|
21
|
+
}[] = [
|
|
22
|
+
{ abbreviation: "5h", id: "five-hour", label: "5h window", windowMinutes: 300 },
|
|
23
|
+
{ abbreviation: "7d", id: "seven-day", label: "Weekly window", windowMinutes: 10_080 },
|
|
24
|
+
];
|
|
25
|
+
|
|
26
|
+
/** Undefined when the headers carry no usable window, so a non-Claude response leaves the last observation alone. */
|
|
27
|
+
export function normalizeClaudeRateLimitHeaders(
|
|
28
|
+
headers: Record<string, string | undefined>,
|
|
29
|
+
capturedAt: number,
|
|
30
|
+
): UsageReport | undefined {
|
|
31
|
+
const lookup = new Map(
|
|
32
|
+
Object.entries(headers).map(([name, value]) => [name.toLowerCase(), value]),
|
|
33
|
+
);
|
|
34
|
+
// The event names no provider, and a model switch mid-stream can deliver a
|
|
35
|
+
// real Anthropic response under claude-bridge with the same header names.
|
|
36
|
+
// Only the bridge's synthetic response consists of nothing but these.
|
|
37
|
+
if ([...lookup.keys()].some((name) => !name.startsWith(HEADER_PREFIX))) {
|
|
38
|
+
return undefined;
|
|
39
|
+
}
|
|
40
|
+
const buckets: UsageBucket[] = [];
|
|
41
|
+
for (const window of CLAUDE_WINDOWS) {
|
|
42
|
+
const utilization = parseNumber(
|
|
43
|
+
lookup.get(`${HEADER_PREFIX}${window.abbreviation}-utilization`),
|
|
44
|
+
);
|
|
45
|
+
if (
|
|
46
|
+
utilization === undefined ||
|
|
47
|
+
utilization < 0 ||
|
|
48
|
+
utilization > MAX_UTILIZATION
|
|
49
|
+
) {
|
|
50
|
+
continue;
|
|
51
|
+
}
|
|
52
|
+
const used = utilization * 100;
|
|
53
|
+
const resetsAt = parseNumber(
|
|
54
|
+
lookup.get(`${HEADER_PREFIX}${window.abbreviation}-reset`),
|
|
55
|
+
);
|
|
56
|
+
buckets.push({
|
|
57
|
+
id: window.id,
|
|
58
|
+
label: window.label,
|
|
59
|
+
used,
|
|
60
|
+
remaining: Math.max(0, 100 - used),
|
|
61
|
+
unit: "percent",
|
|
62
|
+
windowMinutes: window.windowMinutes,
|
|
63
|
+
...(resetsAt !== undefined && resetsAt > 0 && resetsAt < MAX_EPOCH_SECONDS
|
|
64
|
+
? { resetsAt: Math.floor(resetsAt) }
|
|
65
|
+
: {}),
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
if (buckets.length === 0) return undefined;
|
|
69
|
+
return {
|
|
70
|
+
providerId: CLAUDE_BRIDGE_PROVIDER_ID,
|
|
71
|
+
providerName: "Claude (Claude Code)",
|
|
72
|
+
capturedAt,
|
|
73
|
+
source: "claude-code-rate-limit-event",
|
|
74
|
+
semantics: {
|
|
75
|
+
kind: "consumer-subscription",
|
|
76
|
+
label: "Claude subscription limits",
|
|
77
|
+
},
|
|
78
|
+
buckets,
|
|
79
|
+
metrics: [],
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Claude Code only reports usage after a request, so an observation outlives
|
|
85
|
+
* its windows. A window whose reset has passed starts empty; showing the old
|
|
86
|
+
* percentage would overstate usage until the next response.
|
|
87
|
+
*/
|
|
88
|
+
export function settleClaudeReport(
|
|
89
|
+
report: UsageReport,
|
|
90
|
+
nowMs: number,
|
|
91
|
+
): UsageReport {
|
|
92
|
+
const nowSeconds = nowMs / 1_000;
|
|
93
|
+
return {
|
|
94
|
+
...report,
|
|
95
|
+
buckets: report.buckets.map((bucket) => {
|
|
96
|
+
if (bucket.resetsAt === undefined || bucket.resetsAt > nowSeconds) {
|
|
97
|
+
return bucket;
|
|
98
|
+
}
|
|
99
|
+
const { resetsAt: _expired, ...rest } = bucket;
|
|
100
|
+
return { ...rest, used: 0, remaining: 100 };
|
|
101
|
+
}),
|
|
102
|
+
notes: [`Observed after the last Claude response at ${formatClock(report.capturedAt)}; Claude Code reports usage only with its responses.`],
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function parseNumber(value: string | undefined): number | undefined {
|
|
107
|
+
if (value === undefined || !value.trim()) return undefined;
|
|
108
|
+
const parsed = Number(value);
|
|
109
|
+
return Number.isFinite(parsed) ? parsed : undefined;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function formatClock(epochMs: number): string {
|
|
113
|
+
const date = new Date(epochMs);
|
|
114
|
+
if (Number.isNaN(date.getTime())) return "an unknown time";
|
|
115
|
+
const hour = date.getHours().toString().padStart(2, "0");
|
|
116
|
+
const minute = date.getMinutes().toString().padStart(2, "0");
|
|
117
|
+
return `${hour}:${minute}`;
|
|
118
|
+
}
|
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
// Adapted from @narumitw/pi-usage@0.53.0 (MIT).
|
|
2
|
+
import { sanitizeDisplayText } from "../core.ts";
|
|
3
|
+
import type { UsageBucket, UsageMetric, UsageReport } from "../types.ts";
|
|
4
|
+
import {
|
|
5
|
+
CODEX_DEFAULT_GROUP_ID,
|
|
6
|
+
CODEX_PROVIDER_ID,
|
|
7
|
+
} from "./codex-constants.ts";
|
|
8
|
+
|
|
9
|
+
export function normalizeCodexUsage(
|
|
10
|
+
payload: unknown,
|
|
11
|
+
capturedAt: number,
|
|
12
|
+
accountEmail?: string,
|
|
13
|
+
): UsageReport {
|
|
14
|
+
const root = asObject(payload);
|
|
15
|
+
if (!root) throw new Error("Codex usage response was not an object.");
|
|
16
|
+
const buckets: UsageBucket[] = [];
|
|
17
|
+
normalizeRateLimitGroup(
|
|
18
|
+
buckets,
|
|
19
|
+
CODEX_DEFAULT_GROUP_ID,
|
|
20
|
+
"Shared Across Models",
|
|
21
|
+
root.rate_limit,
|
|
22
|
+
false,
|
|
23
|
+
);
|
|
24
|
+
const additional = Array.isArray(root.additional_rate_limits)
|
|
25
|
+
? root.additional_rate_limits
|
|
26
|
+
: [];
|
|
27
|
+
for (const item of additional) {
|
|
28
|
+
const value = asObject(item);
|
|
29
|
+
const id = asString(value?.metered_feature) ?? asString(value?.limit_name);
|
|
30
|
+
if (!value || !id) continue;
|
|
31
|
+
try {
|
|
32
|
+
normalizeRateLimitGroup(
|
|
33
|
+
buckets,
|
|
34
|
+
id,
|
|
35
|
+
asString(value.limit_name) ?? id,
|
|
36
|
+
value.rate_limit,
|
|
37
|
+
true,
|
|
38
|
+
);
|
|
39
|
+
} catch {
|
|
40
|
+
// Optional model-specific buckets must not hide primary usage.
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const metrics: UsageMetric[] = [];
|
|
45
|
+
const credits = asObject(root.credits);
|
|
46
|
+
if (credits?.has_credits === true) {
|
|
47
|
+
if (credits.unlimited === true) {
|
|
48
|
+
metrics.push({
|
|
49
|
+
id: "credits",
|
|
50
|
+
label: "Extra Credit",
|
|
51
|
+
value: "unlimited",
|
|
52
|
+
});
|
|
53
|
+
} else {
|
|
54
|
+
const balance = asNumber(credits.balance);
|
|
55
|
+
metrics.push({
|
|
56
|
+
id: "credits",
|
|
57
|
+
label: "Extra Credit",
|
|
58
|
+
value: balance ?? "available",
|
|
59
|
+
...(balance === undefined ? {} : { unit: "count" as const }),
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
} else if (credits?.has_credits === false) {
|
|
63
|
+
metrics.push({ id: "credits", label: "Extra Credit", value: "none" });
|
|
64
|
+
}
|
|
65
|
+
const resetCredits = asObject(root.rate_limit_reset_credits);
|
|
66
|
+
const resetCount = asNonnegativeInteger(resetCredits?.available_count);
|
|
67
|
+
if (resetCount !== undefined) {
|
|
68
|
+
metrics.push({
|
|
69
|
+
id: "reset-credits",
|
|
70
|
+
label: "Resets Left",
|
|
71
|
+
value: resetCount,
|
|
72
|
+
unit: "count",
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
if (buckets.length === 0 && metrics.length === 0) {
|
|
76
|
+
throw new Error("Codex usage endpoint returned no displayable usage data.");
|
|
77
|
+
}
|
|
78
|
+
addAccountMetrics(metrics, accountEmail, root.plan_type);
|
|
79
|
+
sortAccountMetrics(metrics);
|
|
80
|
+
return {
|
|
81
|
+
providerId: CODEX_PROVIDER_ID,
|
|
82
|
+
providerName: "OpenAI Codex",
|
|
83
|
+
capturedAt,
|
|
84
|
+
source: "codex-pi-auth",
|
|
85
|
+
semantics: {
|
|
86
|
+
kind: "consumer-subscription",
|
|
87
|
+
label: "ChatGPT subscription limits",
|
|
88
|
+
},
|
|
89
|
+
buckets,
|
|
90
|
+
defaultGroupId: CODEX_DEFAULT_GROUP_ID,
|
|
91
|
+
metrics,
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export function codexEmailFromAuthorization(
|
|
96
|
+
authorization: string | undefined,
|
|
97
|
+
): string | undefined {
|
|
98
|
+
const match = /^Bearer\s+(\S+)$/iu.exec(authorization?.trim() ?? "");
|
|
99
|
+
const accessToken = match?.[1];
|
|
100
|
+
if (!accessToken) return undefined;
|
|
101
|
+
try {
|
|
102
|
+
const parts = accessToken.split(".");
|
|
103
|
+
if (parts.length !== 3 || !parts[1]) return undefined;
|
|
104
|
+
const payload = asObject(
|
|
105
|
+
JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8")),
|
|
106
|
+
);
|
|
107
|
+
const profile = asObject(payload?.["https://api.openai.com/profile"]);
|
|
108
|
+
return asEmail(profile?.email) ?? asEmail(payload?.email);
|
|
109
|
+
} catch {
|
|
110
|
+
return undefined;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function addAccountMetrics(
|
|
115
|
+
metrics: UsageMetric[],
|
|
116
|
+
accountEmail: string | undefined,
|
|
117
|
+
planTypeValue: unknown,
|
|
118
|
+
): void {
|
|
119
|
+
const email = asEmail(accountEmail);
|
|
120
|
+
if (email) metrics.unshift({ id: "email", label: "Email", value: email });
|
|
121
|
+
const planType = asString(planTypeValue);
|
|
122
|
+
if (!planType) return;
|
|
123
|
+
metrics.push({
|
|
124
|
+
id: "plan",
|
|
125
|
+
label: "Plan",
|
|
126
|
+
value: planType.toLowerCase() === "pro" ? "Pro" : planType,
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function sortAccountMetrics(metrics: UsageMetric[]): void {
|
|
131
|
+
const order = ["email", "plan", "reset-credits", "credits"];
|
|
132
|
+
metrics.sort((left, right) => {
|
|
133
|
+
const leftRank = order.indexOf(left.id);
|
|
134
|
+
const rightRank = order.indexOf(right.id);
|
|
135
|
+
return (
|
|
136
|
+
(leftRank < 0 ? order.length : leftRank) -
|
|
137
|
+
(rightRank < 0 ? order.length : rightRank)
|
|
138
|
+
);
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function normalizeRateLimitGroup(
|
|
143
|
+
buckets: UsageBucket[],
|
|
144
|
+
groupId: string,
|
|
145
|
+
groupLabel: string,
|
|
146
|
+
raw: unknown,
|
|
147
|
+
optional: boolean,
|
|
148
|
+
): void {
|
|
149
|
+
if (raw === undefined || raw === null) return;
|
|
150
|
+
const details = asObject(raw);
|
|
151
|
+
if (!details) {
|
|
152
|
+
if (optional) return;
|
|
153
|
+
throw new Error("Codex rate limit was not an object.");
|
|
154
|
+
}
|
|
155
|
+
addWindow(buckets, groupId, groupLabel, "primary", details.primary_window);
|
|
156
|
+
addWindow(buckets, groupId, groupLabel, "secondary", details.secondary_window);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function addWindow(
|
|
160
|
+
buckets: UsageBucket[],
|
|
161
|
+
groupId: string,
|
|
162
|
+
groupLabel: string,
|
|
163
|
+
position: "primary" | "secondary",
|
|
164
|
+
raw: unknown,
|
|
165
|
+
): void {
|
|
166
|
+
if (raw === undefined || raw === null) return;
|
|
167
|
+
const value = asObject(raw);
|
|
168
|
+
if (!value) throw new Error("Codex rate-limit window was not an object.");
|
|
169
|
+
const used = asNumber(value.used_percent);
|
|
170
|
+
if (used === undefined) return;
|
|
171
|
+
const clampedUsed = clampPercent(used);
|
|
172
|
+
const seconds = asNumber(value.limit_window_seconds);
|
|
173
|
+
const resetsAt = asNumber(value.reset_at);
|
|
174
|
+
buckets.push({
|
|
175
|
+
id: `${groupId}:${position}`,
|
|
176
|
+
label: position === "primary" ? "Primary limit" : "Secondary limit",
|
|
177
|
+
groupId,
|
|
178
|
+
groupLabel,
|
|
179
|
+
modelKeys: [groupId, groupLabel],
|
|
180
|
+
used: clampedUsed,
|
|
181
|
+
remaining: 100 - clampedUsed,
|
|
182
|
+
limit: 100,
|
|
183
|
+
unit: "percent",
|
|
184
|
+
...(seconds !== undefined && seconds > 0
|
|
185
|
+
? { windowMinutes: Math.ceil(seconds / 60) }
|
|
186
|
+
: {}),
|
|
187
|
+
...(resetsAt === undefined ? {} : { resetsAt }),
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function asObject(value: unknown): Record<string, unknown> | undefined {
|
|
192
|
+
return value && typeof value === "object" && !Array.isArray(value)
|
|
193
|
+
? (value as Record<string, unknown>)
|
|
194
|
+
: undefined;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function asString(value: unknown): string | undefined {
|
|
198
|
+
return typeof value === "string"
|
|
199
|
+
? sanitizeDisplayText(value, 160) || undefined
|
|
200
|
+
: undefined;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
function asEmail(value: unknown): string | undefined {
|
|
204
|
+
if (typeof value !== "string" || value.length > 254) return undefined;
|
|
205
|
+
const email = sanitizeDisplayText(value, 254).toLowerCase();
|
|
206
|
+
return /^[^\s@]+@[^\s@]+$/u.test(email) ? email : undefined;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
function asNumber(value: unknown): number | undefined {
|
|
210
|
+
if (typeof value === "number" && Number.isFinite(value)) return value;
|
|
211
|
+
if (typeof value === "string" && value.trim()) {
|
|
212
|
+
const parsed = Number(value);
|
|
213
|
+
return Number.isFinite(parsed) ? parsed : undefined;
|
|
214
|
+
}
|
|
215
|
+
return undefined;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
function asNonnegativeInteger(value: unknown): number | undefined {
|
|
219
|
+
const parsed = asNumber(value);
|
|
220
|
+
return parsed !== undefined && Number.isSafeInteger(parsed) && parsed >= 0
|
|
221
|
+
? parsed
|
|
222
|
+
: undefined;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
function clampPercent(value: number): number {
|
|
226
|
+
return Math.min(100, Math.max(0, value));
|
|
227
|
+
}
|
|
@@ -0,0 +1,358 @@
|
|
|
1
|
+
// Adapted from pi-grok-usage@1.0.4 (MIT).
|
|
2
|
+
import { sanitizeDisplayText } from "../core.ts";
|
|
3
|
+
import type { UsageBucket, UsageMetric, UsageReport } from "../types.ts";
|
|
4
|
+
|
|
5
|
+
const MAX_USER_ID_LENGTH = 256;
|
|
6
|
+
const MAX_LABEL_LENGTH = 80;
|
|
7
|
+
const MAX_CENTS = 1_000_000_000_000;
|
|
8
|
+
const USER_ID_PATTERN = /^[\x21-\x7e]+$/u;
|
|
9
|
+
const WEEKLY_WINDOW_MINUTES = 10_080;
|
|
10
|
+
const MONTHLY_WINDOW_MINUTES = 43_200;
|
|
11
|
+
// Grok CLI proxy protocol version; independent of this extension's package version.
|
|
12
|
+
const GROK_CLIENT_VERSION = "0.1.0";
|
|
13
|
+
|
|
14
|
+
export function grokRequestHeaders(userId?: string): Record<string, string> {
|
|
15
|
+
return {
|
|
16
|
+
"X-XAI-Token-Auth": "xai-grok-cli",
|
|
17
|
+
"x-grok-client-version": GROK_CLIENT_VERSION,
|
|
18
|
+
"x-grok-client-mode":
|
|
19
|
+
process.stdin.isTTY && process.stdout.isTTY ? "interactive" : "headless",
|
|
20
|
+
...(userId ? { "x-userid": userId } : {}),
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function normalizeGrokIdentity(payload: unknown): string {
|
|
25
|
+
const userId = asObject(payload)?.userId;
|
|
26
|
+
if (
|
|
27
|
+
typeof userId !== "string" ||
|
|
28
|
+
!userId ||
|
|
29
|
+
userId.length > MAX_USER_ID_LENGTH ||
|
|
30
|
+
!USER_ID_PATTERN.test(userId)
|
|
31
|
+
) {
|
|
32
|
+
throw new Error(
|
|
33
|
+
"xAI account identity could not be verified; billing was not requested.",
|
|
34
|
+
);
|
|
35
|
+
}
|
|
36
|
+
return userId;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Unified SuperGrok accounts may expose their quota only on monthly billing. */
|
|
40
|
+
export function shouldProbeGrokMonthly(creditsPayload: unknown): boolean {
|
|
41
|
+
const config = billingConfig(creditsPayload);
|
|
42
|
+
if (!config) return true;
|
|
43
|
+
return (
|
|
44
|
+
config.isUnifiedBillingUser === true ||
|
|
45
|
+
parseCreditsWindow(config) === undefined
|
|
46
|
+
);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** A failed monthly request is fatal when credits contain no reliable quota. */
|
|
50
|
+
export function requiresGrokMonthlyQuota(creditsPayload: unknown): boolean {
|
|
51
|
+
return parseCreditsWindow(billingConfig(creditsPayload)) === undefined;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function normalizeGrokBilling(
|
|
55
|
+
creditsPayload: unknown,
|
|
56
|
+
capturedAt: number,
|
|
57
|
+
monthlyPayload?: unknown | null,
|
|
58
|
+
): UsageReport {
|
|
59
|
+
const creditsRoot = asObject(creditsPayload);
|
|
60
|
+
if (!creditsRoot) throw new Error("Grok billing response was not an object.");
|
|
61
|
+
const creditsConfig = billingConfig(creditsPayload);
|
|
62
|
+
const weekly = parseCreditsWindow(creditsConfig);
|
|
63
|
+
|
|
64
|
+
const monthlyRoot = readOptionalPayload(
|
|
65
|
+
monthlyPayload,
|
|
66
|
+
"Grok monthly billing response was not an object.",
|
|
67
|
+
);
|
|
68
|
+
let monthlyConfig: Record<string, unknown> | undefined;
|
|
69
|
+
if (monthlyRoot !== undefined) {
|
|
70
|
+
monthlyConfig = billingConfig(monthlyRoot, "skip");
|
|
71
|
+
} else if (monthlyPayload === undefined && !weekly) {
|
|
72
|
+
monthlyConfig = creditsConfig;
|
|
73
|
+
}
|
|
74
|
+
const monthly = parseMonthlyWindow(monthlyConfig);
|
|
75
|
+
|
|
76
|
+
const buckets: UsageBucket[] = [];
|
|
77
|
+
if (weekly) buckets.push(weekly);
|
|
78
|
+
if (monthly) buckets.push(monthly);
|
|
79
|
+
if (buckets.length === 0) {
|
|
80
|
+
throw new Error(
|
|
81
|
+
"Grok billing endpoint returned no displayable quota window.",
|
|
82
|
+
);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const primaryMetrics = collectMetrics(creditsConfig);
|
|
86
|
+
addAccountMetrics(primaryMetrics, creditsRoot);
|
|
87
|
+
const extraMetrics =
|
|
88
|
+
monthlyConfig && monthlyConfig !== creditsConfig
|
|
89
|
+
? collectMetrics(monthlyConfig)
|
|
90
|
+
: [];
|
|
91
|
+
if (monthlyRoot) addAccountMetrics(extraMetrics, monthlyRoot);
|
|
92
|
+
const metrics = mergeMetrics(primaryMetrics, extraMetrics);
|
|
93
|
+
|
|
94
|
+
return {
|
|
95
|
+
providerId: "xai",
|
|
96
|
+
providerName: "Grok",
|
|
97
|
+
capturedAt,
|
|
98
|
+
source: "grok-cli-billing",
|
|
99
|
+
semantics: {
|
|
100
|
+
kind: "consumer-subscription",
|
|
101
|
+
label: "SuperGrok subscription usage",
|
|
102
|
+
},
|
|
103
|
+
buckets,
|
|
104
|
+
metrics,
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function readOptionalPayload(
|
|
109
|
+
payload: unknown | null | undefined,
|
|
110
|
+
invalidMessage: string,
|
|
111
|
+
): Record<string, unknown> | undefined {
|
|
112
|
+
if (payload === undefined || payload === null) return undefined;
|
|
113
|
+
const root = asObject(payload);
|
|
114
|
+
if (!root) throw new Error(invalidMessage);
|
|
115
|
+
return root;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function billingConfig(
|
|
119
|
+
payload: unknown,
|
|
120
|
+
invalidConfig: "throw" | "skip" = "throw",
|
|
121
|
+
): Record<string, unknown> | undefined {
|
|
122
|
+
const root = asObject(payload);
|
|
123
|
+
if (!root) return undefined;
|
|
124
|
+
if (root.config === undefined) return undefined;
|
|
125
|
+
const config = asObject(root.config);
|
|
126
|
+
if (!config) {
|
|
127
|
+
if (invalidConfig === "skip") return undefined;
|
|
128
|
+
throw new Error("Grok billing response contained an invalid config object.");
|
|
129
|
+
}
|
|
130
|
+
return config;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function parseCreditsWindow(
|
|
134
|
+
config: Record<string, unknown> | undefined,
|
|
135
|
+
): UsageBucket | undefined {
|
|
136
|
+
if (!config) return undefined;
|
|
137
|
+
const period = asObject(config.currentPeriod);
|
|
138
|
+
let used = boundedPercent(config.creditUsagePercent);
|
|
139
|
+
if (used === undefined && isWeeklyPeriod(period)) {
|
|
140
|
+
const usedCents = boundedCents(config.used);
|
|
141
|
+
const limitCents = boundedCents(config.monthlyLimit);
|
|
142
|
+
if (usedCents !== undefined && limitCents !== undefined && limitCents > 0) {
|
|
143
|
+
used = Math.min(100, (usedCents / limitCents) * 100);
|
|
144
|
+
} else if (
|
|
145
|
+
config.creditUsagePercent === undefined &&
|
|
146
|
+
config.used === undefined &&
|
|
147
|
+
config.monthlyLimit === undefined
|
|
148
|
+
) {
|
|
149
|
+
// Proto3 JSON omits creditUsagePercent when it is 0, which happens
|
|
150
|
+
// at weekly reset. Official Grok CLI still treats that as 0% used.
|
|
151
|
+
// Only do this when the fields are absent, not present-but-invalid.
|
|
152
|
+
used = 0;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
if (used === undefined) return undefined;
|
|
156
|
+
return percentWindow("weekly", used, config, period, WEEKLY_WINDOW_MINUTES);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function parseMonthlyWindow(
|
|
160
|
+
config: Record<string, unknown> | undefined,
|
|
161
|
+
): UsageBucket | undefined {
|
|
162
|
+
if (!config) return undefined;
|
|
163
|
+
const usedCents = boundedCents(config.used);
|
|
164
|
+
const limitCents = boundedCents(config.monthlyLimit);
|
|
165
|
+
if (usedCents === undefined || limitCents === undefined || limitCents <= 0) {
|
|
166
|
+
return undefined;
|
|
167
|
+
}
|
|
168
|
+
const used = Math.min(100, (usedCents / limitCents) * 100);
|
|
169
|
+
const period = asObject(config.currentPeriod);
|
|
170
|
+
return percentWindow(
|
|
171
|
+
"monthly",
|
|
172
|
+
used,
|
|
173
|
+
config,
|
|
174
|
+
isWeeklyPeriod(period) ? undefined : period,
|
|
175
|
+
MONTHLY_WINDOW_MINUTES,
|
|
176
|
+
);
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
function percentWindow(
|
|
180
|
+
kind: "weekly" | "monthly",
|
|
181
|
+
used: number,
|
|
182
|
+
config: Record<string, unknown>,
|
|
183
|
+
period: Record<string, unknown> | undefined,
|
|
184
|
+
fallbackMinutes: number,
|
|
185
|
+
): UsageBucket {
|
|
186
|
+
const periodInfo = parseUsagePeriod(config, period);
|
|
187
|
+
const bucket: UsageBucket = {
|
|
188
|
+
id: kind,
|
|
189
|
+
label: kind === "monthly" ? "Monthly window" : "Weekly window",
|
|
190
|
+
used,
|
|
191
|
+
remaining: 100 - used,
|
|
192
|
+
limit: 100,
|
|
193
|
+
unit: "percent",
|
|
194
|
+
period: kind,
|
|
195
|
+
windowMinutes:
|
|
196
|
+
periodInfo.period === kind
|
|
197
|
+
? (periodInfo.windowMinutes ?? fallbackMinutes)
|
|
198
|
+
: fallbackMinutes,
|
|
199
|
+
};
|
|
200
|
+
const resetsAt = parseTimestamp(
|
|
201
|
+
kind === "monthly"
|
|
202
|
+
? (config.billingPeriodEnd ?? period?.end)
|
|
203
|
+
: (period?.end ?? config.billingPeriodEnd),
|
|
204
|
+
);
|
|
205
|
+
if (resetsAt !== undefined) bucket.resetsAt = resetsAt;
|
|
206
|
+
return bucket;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
function parseUsagePeriod(
|
|
210
|
+
config: Record<string, unknown> | undefined,
|
|
211
|
+
currentPeriod: Record<string, unknown> | undefined,
|
|
212
|
+
): Pick<UsageBucket, "period" | "windowMinutes"> {
|
|
213
|
+
const type = currentPeriod?.type;
|
|
214
|
+
if (typeof type === "string") {
|
|
215
|
+
if (type.toUpperCase().includes("WEEKLY")) {
|
|
216
|
+
return { period: "weekly", windowMinutes: WEEKLY_WINDOW_MINUTES };
|
|
217
|
+
}
|
|
218
|
+
if (type.toUpperCase().includes("MONTHLY")) {
|
|
219
|
+
return { period: "monthly", windowMinutes: MONTHLY_WINDOW_MINUTES };
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
const start = parseTimestamp(
|
|
223
|
+
currentPeriod?.start ?? config?.billingPeriodStart,
|
|
224
|
+
);
|
|
225
|
+
const end = parseTimestamp(currentPeriod?.end ?? config?.billingPeriodEnd);
|
|
226
|
+
if (start === undefined || end === undefined || end <= start) return {};
|
|
227
|
+
const windowMinutes = Math.round((end - start) / 60);
|
|
228
|
+
if (windowMinutes >= 6 * 24 * 60 && windowMinutes <= 8 * 24 * 60) {
|
|
229
|
+
return { period: "weekly", windowMinutes };
|
|
230
|
+
}
|
|
231
|
+
if (windowMinutes >= 28 * 24 * 60 && windowMinutes <= 31 * 24 * 60) {
|
|
232
|
+
return { period: "monthly", windowMinutes };
|
|
233
|
+
}
|
|
234
|
+
return { windowMinutes };
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
function isWeeklyPeriod(
|
|
238
|
+
period: Record<string, unknown> | undefined,
|
|
239
|
+
): period is Record<string, unknown> {
|
|
240
|
+
return (
|
|
241
|
+
typeof period?.type === "string" && period.type.toUpperCase().includes("WEEK")
|
|
242
|
+
);
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
function collectMetrics(
|
|
246
|
+
config: Record<string, unknown> | undefined,
|
|
247
|
+
): UsageMetric[] {
|
|
248
|
+
const metrics: UsageMetric[] = [];
|
|
249
|
+
addUsdMetric(
|
|
250
|
+
metrics,
|
|
251
|
+
"included-used",
|
|
252
|
+
"Included Used",
|
|
253
|
+
boundedCents(config?.used),
|
|
254
|
+
);
|
|
255
|
+
addUsdMetric(
|
|
256
|
+
metrics,
|
|
257
|
+
"included-limit",
|
|
258
|
+
"Included Total",
|
|
259
|
+
boundedCents(config?.monthlyLimit),
|
|
260
|
+
);
|
|
261
|
+
addUsdMetric(
|
|
262
|
+
metrics,
|
|
263
|
+
"on-demand-used",
|
|
264
|
+
"On-Demand Used",
|
|
265
|
+
boundedCents(config?.onDemandUsed),
|
|
266
|
+
);
|
|
267
|
+
addUsdMetric(
|
|
268
|
+
metrics,
|
|
269
|
+
"on-demand-cap",
|
|
270
|
+
"On-Demand Cap",
|
|
271
|
+
boundedCents(config?.onDemandCap),
|
|
272
|
+
);
|
|
273
|
+
addUsdMetric(
|
|
274
|
+
metrics,
|
|
275
|
+
"prepaid-balance",
|
|
276
|
+
"Prepaid Balance",
|
|
277
|
+
boundedCents(config?.prepaidBalance),
|
|
278
|
+
);
|
|
279
|
+
return metrics;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
function addAccountMetrics(
|
|
283
|
+
metrics: UsageMetric[],
|
|
284
|
+
root: Record<string, unknown>,
|
|
285
|
+
): void {
|
|
286
|
+
const tier = boundedLabel(root.subscriptionTier);
|
|
287
|
+
if (tier) metrics.push({ id: "plan", label: "Plan", value: tier });
|
|
288
|
+
if (typeof root.onDemandEnabled === "boolean") {
|
|
289
|
+
metrics.push({
|
|
290
|
+
id: "on-demand",
|
|
291
|
+
label: "On-Demand",
|
|
292
|
+
value: root.onDemandEnabled ? "on" : "off",
|
|
293
|
+
});
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
function mergeMetrics(
|
|
298
|
+
primary: UsageMetric[],
|
|
299
|
+
extra: UsageMetric[],
|
|
300
|
+
): UsageMetric[] {
|
|
301
|
+
const seen = new Set(primary.map((metric) => metric.id));
|
|
302
|
+
return [
|
|
303
|
+
...primary,
|
|
304
|
+
...extra.filter((metric) => {
|
|
305
|
+
if (seen.has(metric.id)) return false;
|
|
306
|
+
seen.add(metric.id);
|
|
307
|
+
return true;
|
|
308
|
+
}),
|
|
309
|
+
];
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
function addUsdMetric(
|
|
313
|
+
metrics: UsageMetric[],
|
|
314
|
+
id: string,
|
|
315
|
+
label: string,
|
|
316
|
+
cents: number | undefined,
|
|
317
|
+
): void {
|
|
318
|
+
if (cents === undefined) return;
|
|
319
|
+
metrics.push({ id, label, value: cents / 100, unit: "usd" });
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
function asObject(value: unknown): Record<string, unknown> | undefined {
|
|
323
|
+
return value && typeof value === "object" && !Array.isArray(value)
|
|
324
|
+
? (value as Record<string, unknown>)
|
|
325
|
+
: undefined;
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
function boundedLabel(value: unknown): string | undefined {
|
|
329
|
+
if (typeof value !== "string") return undefined;
|
|
330
|
+
const label = sanitizeDisplayText(value, MAX_LABEL_LENGTH);
|
|
331
|
+
return label || undefined;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
function boundedPercent(value: unknown): number | undefined {
|
|
335
|
+
return typeof value === "number" &&
|
|
336
|
+
Number.isFinite(value) &&
|
|
337
|
+
value >= 0 &&
|
|
338
|
+
value <= 100
|
|
339
|
+
? value
|
|
340
|
+
: undefined;
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
function boundedCents(value: unknown): number | undefined {
|
|
344
|
+
const wrapper = asObject(value);
|
|
345
|
+
const raw = wrapper ? wrapper.val : value;
|
|
346
|
+
return typeof raw === "number" &&
|
|
347
|
+
Number.isSafeInteger(raw) &&
|
|
348
|
+
raw >= 0 &&
|
|
349
|
+
raw <= MAX_CENTS
|
|
350
|
+
? raw
|
|
351
|
+
: undefined;
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
function parseTimestamp(value: unknown): number | undefined {
|
|
355
|
+
if (typeof value !== "string" || value.length > 64) return undefined;
|
|
356
|
+
const parsed = Date.parse(value);
|
|
357
|
+
return Number.isNaN(parsed) ? undefined : Math.floor(parsed / 1000);
|
|
358
|
+
}
|