@specode/pi-subscription-usage 0.2.0 → 0.2.1
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/package.json +1 -1
- package/src/codex-resets.ts +5 -4
- package/src/format.ts +9 -35
- package/src/providers/codex-constants.ts +2 -0
- package/src/providers/codex.ts +25 -9
- package/src/providers/grok.ts +29 -16
- package/src/providers/opencode-go.ts +3 -2
- package/src/query.ts +22 -33
- package/src/status.ts +27 -25
- package/src/types.ts +2 -0
- package/src/usage.ts +30 -11
package/package.json
CHANGED
package/src/codex-resets.ts
CHANGED
|
@@ -19,6 +19,7 @@ import {
|
|
|
19
19
|
resolveUsageAuth,
|
|
20
20
|
} from "./query.ts";
|
|
21
21
|
import type { ResolvedUsageAuth } from "./types.ts";
|
|
22
|
+
import { CODEX_PROVIDER_ID } from "./providers/codex-constants.ts";
|
|
22
23
|
|
|
23
24
|
const RESET_CREDITS_URL =
|
|
24
25
|
"https://chatgpt.com/backend-api/wham/rate-limit-reset-credits";
|
|
@@ -32,13 +33,13 @@ export async function resolveCodexResetAuth(
|
|
|
32
33
|
credentialReader: StoredCredentialReader = readStoredCredential,
|
|
33
34
|
): Promise<ResolvedUsageAuth> {
|
|
34
35
|
const model = ctx.model;
|
|
35
|
-
if (model?.provider !==
|
|
36
|
+
if (model?.provider !== CODEX_PROVIDER_ID) {
|
|
36
37
|
throw new Error(
|
|
37
38
|
"Codex resets require the current model to use OpenAI Codex.",
|
|
38
39
|
);
|
|
39
40
|
}
|
|
40
41
|
const expectedModel = `${model.provider}/${model.id}`;
|
|
41
|
-
const adapter = adapterForProvider(
|
|
42
|
+
const adapter = adapterForProvider(CODEX_PROVIDER_ID);
|
|
42
43
|
if (!adapter) throw new Error("OpenAI Codex usage support is unavailable.");
|
|
43
44
|
const auth = await resolveUsageAuth(ctx, adapter, salt);
|
|
44
45
|
if (`${ctx.model?.provider}/${ctx.model?.id}` !== expectedModel) {
|
|
@@ -55,7 +56,7 @@ export async function resolveCodexResetAuth(
|
|
|
55
56
|
throw new Error("OpenAI Codex OAuth credentials were incomplete.");
|
|
56
57
|
const accountId = verifyCodexStoredOAuthCredential(
|
|
57
58
|
resolvedAccess,
|
|
58
|
-
credentialReader(
|
|
59
|
+
credentialReader(CODEX_PROVIDER_ID),
|
|
59
60
|
);
|
|
60
61
|
const authorization = `Bearer ${resolvedAccess}`;
|
|
61
62
|
const headers = {
|
|
@@ -63,7 +64,7 @@ export async function resolveCodexResetAuth(
|
|
|
63
64
|
"chatgpt-account-id": accountId,
|
|
64
65
|
};
|
|
65
66
|
return {
|
|
66
|
-
actualProviderId:
|
|
67
|
+
actualProviderId: CODEX_PROVIDER_ID,
|
|
67
68
|
apiKey: resolvedAccess,
|
|
68
69
|
headers,
|
|
69
70
|
fingerprint: fingerprintResolvedAuth({ headers }, salt),
|
package/src/format.ts
CHANGED
|
@@ -31,9 +31,9 @@ export function formatUsageReport(
|
|
|
31
31
|
report: UsageReport,
|
|
32
32
|
displayMode: UsageDisplayMode = DEFAULT_USAGE_DISPLAY_MODE,
|
|
33
33
|
): string {
|
|
34
|
-
const sections = bucketSections(report
|
|
34
|
+
const sections = bucketSections(report, displayMode);
|
|
35
35
|
const accountRows: PanelRow[] = report.metrics.map((metric) => ({
|
|
36
|
-
label:
|
|
36
|
+
label: metric.label,
|
|
37
37
|
detail: formatMetric(metric),
|
|
38
38
|
}));
|
|
39
39
|
for (const note of report.notes ?? []) accountRows.push(noteRow(note));
|
|
@@ -106,13 +106,13 @@ function formatBucket(
|
|
|
106
106
|
}
|
|
107
107
|
|
|
108
108
|
function bucketSections(
|
|
109
|
-
|
|
109
|
+
report: UsageReport,
|
|
110
110
|
displayMode: UsageDisplayMode,
|
|
111
111
|
): PanelSection[] {
|
|
112
|
-
if (!buckets.some((bucket) => bucket.groupId)) {
|
|
112
|
+
if (!report.buckets.some((bucket) => bucket.groupId)) {
|
|
113
113
|
return [
|
|
114
114
|
{
|
|
115
|
-
rows: sortUsageBuckets(buckets).map((bucket) => ({
|
|
115
|
+
rows: sortUsageBuckets(report.buckets).map((bucket) => ({
|
|
116
116
|
label: usageWindowLabel(bucket),
|
|
117
117
|
detail: formatBucket(bucket, displayMode),
|
|
118
118
|
})),
|
|
@@ -120,15 +120,12 @@ function bucketSections(
|
|
|
120
120
|
];
|
|
121
121
|
}
|
|
122
122
|
const groups = new Map<string, { heading: string; buckets: UsageBucket[] }>();
|
|
123
|
-
for (const bucket of buckets) {
|
|
123
|
+
for (const bucket of report.buckets) {
|
|
124
124
|
const key = bucket.groupId ?? "other";
|
|
125
125
|
let group = groups.get(key);
|
|
126
126
|
if (!group) {
|
|
127
127
|
group = {
|
|
128
|
-
heading:
|
|
129
|
-
key === "codex"
|
|
130
|
-
? "Shared Across Models"
|
|
131
|
-
: (bucket.groupLabel ?? bucket.groupId ?? "Other Quota"),
|
|
128
|
+
heading: bucket.groupLabel ?? bucket.groupId ?? "Other Quota",
|
|
132
129
|
buckets: [],
|
|
133
130
|
};
|
|
134
131
|
groups.set(key, group);
|
|
@@ -137,8 +134,8 @@ function bucketSections(
|
|
|
137
134
|
}
|
|
138
135
|
return [...groups.entries()]
|
|
139
136
|
.sort(([leftKey, left], [rightKey, right]) => {
|
|
140
|
-
if (leftKey ===
|
|
141
|
-
if (rightKey ===
|
|
137
|
+
if (leftKey === report.defaultGroupId) return -1;
|
|
138
|
+
if (rightKey === report.defaultGroupId) return 1;
|
|
142
139
|
return left.heading.localeCompare(right.heading);
|
|
143
140
|
})
|
|
144
141
|
.map(([, group]) => ({
|
|
@@ -161,34 +158,11 @@ function formatPanelRows(
|
|
|
161
158
|
);
|
|
162
159
|
}
|
|
163
160
|
|
|
164
|
-
function metricLabel(metric: UsageMetric): string {
|
|
165
|
-
if (metric.id === "reset-credits") return "Resets Left";
|
|
166
|
-
if (metric.id === "credits") return "Extra Credit";
|
|
167
|
-
if (metric.id === "included-used") return "Included Used";
|
|
168
|
-
if (metric.id === "included-limit") return "Included Total";
|
|
169
|
-
if (metric.id === "on-demand-used") return "On-Demand Used";
|
|
170
|
-
if (metric.id === "on-demand-cap") return "On-Demand Cap";
|
|
171
|
-
if (metric.id === "prepaid-balance") return "Prepaid Balance";
|
|
172
|
-
return metric.label;
|
|
173
|
-
}
|
|
174
|
-
|
|
175
161
|
function formatMetric(metric: UsageMetric): string {
|
|
176
|
-
if (metric.id === "reset-credits" && typeof metric.value === "number") {
|
|
177
|
-
return formatNumber(metric.value);
|
|
178
|
-
}
|
|
179
162
|
return formatValue(metric.value, metric.unit);
|
|
180
163
|
}
|
|
181
164
|
|
|
182
165
|
function noteRow(note: string): PanelRow {
|
|
183
|
-
if (note.startsWith("Plan: ")) {
|
|
184
|
-
return { label: "Plan", detail: note.slice("Plan: ".length) };
|
|
185
|
-
}
|
|
186
|
-
if (note === "On-demand billing: enabled") {
|
|
187
|
-
return { label: "On-Demand", detail: "on" };
|
|
188
|
-
}
|
|
189
|
-
if (note === "On-demand billing: disabled") {
|
|
190
|
-
return { label: "On-Demand", detail: "off" };
|
|
191
|
-
}
|
|
192
166
|
return { label: "Note", detail: note };
|
|
193
167
|
}
|
|
194
168
|
|
package/src/providers/codex.ts
CHANGED
|
@@ -1,6 +1,10 @@
|
|
|
1
1
|
// Adapted from @narumitw/pi-usage@0.53.0 (MIT).
|
|
2
2
|
import { sanitizeDisplayText } from "../core.ts";
|
|
3
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";
|
|
4
8
|
|
|
5
9
|
export function normalizeCodexUsage(
|
|
6
10
|
payload: unknown,
|
|
@@ -9,7 +13,13 @@ export function normalizeCodexUsage(
|
|
|
9
13
|
const root = asObject(payload);
|
|
10
14
|
if (!root) throw new Error("Codex usage response was not an object.");
|
|
11
15
|
const buckets: UsageBucket[] = [];
|
|
12
|
-
normalizeRateLimitGroup(
|
|
16
|
+
normalizeRateLimitGroup(
|
|
17
|
+
buckets,
|
|
18
|
+
CODEX_DEFAULT_GROUP_ID,
|
|
19
|
+
"Shared Across Models",
|
|
20
|
+
root.rate_limit,
|
|
21
|
+
false,
|
|
22
|
+
);
|
|
13
23
|
const additional = Array.isArray(root.additional_rate_limits)
|
|
14
24
|
? root.additional_rate_limits
|
|
15
25
|
: [];
|
|
@@ -34,25 +44,29 @@ export function normalizeCodexUsage(
|
|
|
34
44
|
const credits = asObject(root.credits);
|
|
35
45
|
if (credits?.has_credits === true) {
|
|
36
46
|
if (credits.unlimited === true) {
|
|
37
|
-
metrics.push({
|
|
47
|
+
metrics.push({
|
|
48
|
+
id: "credits",
|
|
49
|
+
label: "Extra Credit",
|
|
50
|
+
value: "unlimited",
|
|
51
|
+
});
|
|
38
52
|
} else {
|
|
39
53
|
const balance = asNumber(credits.balance);
|
|
40
54
|
metrics.push({
|
|
41
55
|
id: "credits",
|
|
42
|
-
label: "
|
|
56
|
+
label: "Extra Credit",
|
|
43
57
|
value: balance ?? "available",
|
|
44
58
|
...(balance === undefined ? {} : { unit: "count" as const }),
|
|
45
59
|
});
|
|
46
60
|
}
|
|
47
61
|
} else if (credits?.has_credits === false) {
|
|
48
|
-
metrics.push({ id: "credits", label: "
|
|
62
|
+
metrics.push({ id: "credits", label: "Extra Credit", value: "none" });
|
|
49
63
|
}
|
|
50
64
|
const resetCredits = asObject(root.rate_limit_reset_credits);
|
|
51
65
|
const resetCount = asNonnegativeInteger(resetCredits?.available_count);
|
|
52
66
|
if (resetCount !== undefined) {
|
|
53
67
|
metrics.push({
|
|
54
68
|
id: "reset-credits",
|
|
55
|
-
label: "
|
|
69
|
+
label: "Resets Left",
|
|
56
70
|
value: resetCount,
|
|
57
71
|
unit: "count",
|
|
58
72
|
});
|
|
@@ -61,8 +75,9 @@ export function normalizeCodexUsage(
|
|
|
61
75
|
throw new Error("Codex usage endpoint returned no displayable usage data.");
|
|
62
76
|
}
|
|
63
77
|
const planType = asString(root.plan_type);
|
|
78
|
+
if (planType) metrics.push({ id: "plan", label: "Plan", value: planType });
|
|
64
79
|
return {
|
|
65
|
-
providerId:
|
|
80
|
+
providerId: CODEX_PROVIDER_ID,
|
|
66
81
|
providerName: "OpenAI Codex",
|
|
67
82
|
capturedAt,
|
|
68
83
|
source: "codex-pi-auth",
|
|
@@ -71,8 +86,8 @@ export function normalizeCodexUsage(
|
|
|
71
86
|
label: "ChatGPT subscription limits",
|
|
72
87
|
},
|
|
73
88
|
buckets,
|
|
89
|
+
defaultGroupId: CODEX_DEFAULT_GROUP_ID,
|
|
74
90
|
metrics,
|
|
75
|
-
...(planType ? { notes: [`Plan: ${planType}`] } : {}),
|
|
76
91
|
};
|
|
77
92
|
}
|
|
78
93
|
|
|
@@ -105,6 +120,7 @@ function addWindow(
|
|
|
105
120
|
if (!value) throw new Error("Codex rate-limit window was not an object.");
|
|
106
121
|
const used = asNumber(value.used_percent);
|
|
107
122
|
if (used === undefined) return;
|
|
123
|
+
const clampedUsed = clampPercent(used);
|
|
108
124
|
const seconds = asNumber(value.limit_window_seconds);
|
|
109
125
|
const resetsAt = asNumber(value.reset_at);
|
|
110
126
|
buckets.push({
|
|
@@ -113,8 +129,8 @@ function addWindow(
|
|
|
113
129
|
groupId,
|
|
114
130
|
groupLabel,
|
|
115
131
|
modelKeys: [groupId, groupLabel],
|
|
116
|
-
used,
|
|
117
|
-
remaining: 100 -
|
|
132
|
+
used: clampedUsed,
|
|
133
|
+
remaining: 100 - clampedUsed,
|
|
118
134
|
limit: 100,
|
|
119
135
|
unit: "percent",
|
|
120
136
|
...(seconds !== undefined && seconds > 0
|
package/src/providers/grok.ts
CHANGED
|
@@ -6,6 +6,18 @@ const MAX_USER_ID_LENGTH = 256;
|
|
|
6
6
|
const MAX_LABEL_LENGTH = 80;
|
|
7
7
|
const MAX_CENTS = 1_000_000_000_000;
|
|
8
8
|
const USER_ID_PATTERN = /^[\x21-\x7e]+$/u;
|
|
9
|
+
// Grok CLI proxy protocol version; independent of this extension's package version.
|
|
10
|
+
const GROK_CLIENT_VERSION = "0.1.0";
|
|
11
|
+
|
|
12
|
+
export function grokRequestHeaders(userId?: string): Record<string, string> {
|
|
13
|
+
return {
|
|
14
|
+
"X-XAI-Token-Auth": "xai-grok-cli",
|
|
15
|
+
"x-grok-client-version": GROK_CLIENT_VERSION,
|
|
16
|
+
"x-grok-client-mode":
|
|
17
|
+
process.stdin.isTTY && process.stdout.isTTY ? "interactive" : "headless",
|
|
18
|
+
...(userId ? { "x-userid": userId } : {}),
|
|
19
|
+
};
|
|
20
|
+
}
|
|
9
21
|
|
|
10
22
|
export function normalizeGrokIdentity(payload: unknown): string {
|
|
11
23
|
const userId = asObject(payload)?.userId;
|
|
@@ -38,8 +50,8 @@ export function normalizeGrokBilling(
|
|
|
38
50
|
if (buckets.length === 0 && metrics.length === 0) {
|
|
39
51
|
throw new Error("Grok billing endpoint returned no displayable usage data.");
|
|
40
52
|
}
|
|
41
|
-
|
|
42
|
-
|
|
53
|
+
addAccountMetrics(metrics, root);
|
|
54
|
+
return {
|
|
43
55
|
providerId: "xai",
|
|
44
56
|
providerName: "Grok",
|
|
45
57
|
capturedAt,
|
|
@@ -51,8 +63,6 @@ export function normalizeGrokBilling(
|
|
|
51
63
|
buckets,
|
|
52
64
|
metrics,
|
|
53
65
|
};
|
|
54
|
-
if (notes.length > 0) report.notes = notes;
|
|
55
|
-
return report;
|
|
56
66
|
}
|
|
57
67
|
|
|
58
68
|
function createIncludedBucket(
|
|
@@ -122,46 +132,49 @@ function collectMetrics(
|
|
|
122
132
|
addUsdMetric(
|
|
123
133
|
metrics,
|
|
124
134
|
"included-used",
|
|
125
|
-
"Included
|
|
135
|
+
"Included Used",
|
|
126
136
|
boundedCents(config?.used),
|
|
127
137
|
);
|
|
128
138
|
addUsdMetric(
|
|
129
139
|
metrics,
|
|
130
140
|
"included-limit",
|
|
131
|
-
"Included
|
|
141
|
+
"Included Total",
|
|
132
142
|
boundedCents(config?.monthlyLimit),
|
|
133
143
|
);
|
|
134
144
|
addUsdMetric(
|
|
135
145
|
metrics,
|
|
136
146
|
"on-demand-used",
|
|
137
|
-
"On-
|
|
147
|
+
"On-Demand Used",
|
|
138
148
|
boundedCents(config?.onDemandUsed),
|
|
139
149
|
);
|
|
140
150
|
addUsdMetric(
|
|
141
151
|
metrics,
|
|
142
152
|
"on-demand-cap",
|
|
143
|
-
"On-
|
|
153
|
+
"On-Demand Cap",
|
|
144
154
|
boundedCents(config?.onDemandCap),
|
|
145
155
|
);
|
|
146
156
|
addUsdMetric(
|
|
147
157
|
metrics,
|
|
148
158
|
"prepaid-balance",
|
|
149
|
-
"Prepaid
|
|
159
|
+
"Prepaid Balance",
|
|
150
160
|
boundedCents(config?.prepaidBalance),
|
|
151
161
|
);
|
|
152
162
|
return metrics;
|
|
153
163
|
}
|
|
154
164
|
|
|
155
|
-
function
|
|
156
|
-
|
|
165
|
+
function addAccountMetrics(
|
|
166
|
+
metrics: UsageMetric[],
|
|
167
|
+
root: Record<string, unknown>,
|
|
168
|
+
): void {
|
|
157
169
|
const tier = boundedLabel(root.subscriptionTier);
|
|
158
|
-
if (tier)
|
|
170
|
+
if (tier) metrics.push({ id: "plan", label: "Plan", value: tier });
|
|
159
171
|
if (typeof root.onDemandEnabled === "boolean") {
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
172
|
+
metrics.push({
|
|
173
|
+
id: "on-demand",
|
|
174
|
+
label: "On-Demand",
|
|
175
|
+
value: root.onDemandEnabled ? "on" : "off",
|
|
176
|
+
});
|
|
163
177
|
}
|
|
164
|
-
return notes;
|
|
165
178
|
}
|
|
166
179
|
|
|
167
180
|
function addUsdMetric(
|
|
@@ -29,12 +29,13 @@ export function normalizeOpenCodeGoUsage(
|
|
|
29
29
|
}
|
|
30
30
|
const used = asNonnegativeNumber(raw.percent);
|
|
31
31
|
if (used === undefined) continue;
|
|
32
|
+
const clampedUsed = clampPercent(used);
|
|
32
33
|
const resetsAt = asEpochSeconds(raw.resetsAt);
|
|
33
34
|
buckets.push({
|
|
34
35
|
id: window.key,
|
|
35
36
|
label: `${window.label} window`,
|
|
36
|
-
used,
|
|
37
|
-
remaining: 100 -
|
|
37
|
+
used: clampedUsed,
|
|
38
|
+
remaining: 100 - clampedUsed,
|
|
38
39
|
limit: 100,
|
|
39
40
|
unit: "percent",
|
|
40
41
|
windowMinutes: window.windowMinutes,
|
package/src/query.ts
CHANGED
|
@@ -1,13 +1,16 @@
|
|
|
1
1
|
// Runtime-auth and origin checks adapted from @narumitw/pi-usage@0.53.0 (MIT).
|
|
2
2
|
import { randomBytes } from "node:crypto";
|
|
3
|
+
import { createRequire } from "node:module";
|
|
3
4
|
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
4
5
|
import {
|
|
5
6
|
errorMessage,
|
|
6
7
|
fingerprintResolvedAuth,
|
|
7
8
|
redactUsageError,
|
|
8
9
|
} from "./core.ts";
|
|
10
|
+
import { CODEX_PROVIDER_ID } from "./providers/codex-constants.ts";
|
|
9
11
|
import { normalizeCodexUsage } from "./providers/codex.ts";
|
|
10
12
|
import {
|
|
13
|
+
grokRequestHeaders,
|
|
11
14
|
normalizeGrokBilling,
|
|
12
15
|
normalizeGrokIdentity,
|
|
13
16
|
} from "./providers/grok.ts";
|
|
@@ -27,6 +30,11 @@ const GROK_BILLING_URL =
|
|
|
27
30
|
"https://cli-chat-proxy.grok.com/v1/billing?format=credits";
|
|
28
31
|
const MAX_SUCCESS_BODY_BYTES = 64 * 1024;
|
|
29
32
|
const MAX_ERROR_BODY_BYTES = 4 * 1024;
|
|
33
|
+
const PACKAGE_METADATA = createRequire(import.meta.url)("../package.json") as {
|
|
34
|
+
name: string;
|
|
35
|
+
version: string;
|
|
36
|
+
};
|
|
37
|
+
const USER_AGENT = `${PACKAGE_METADATA.name}/${PACKAGE_METADATA.version}`;
|
|
30
38
|
|
|
31
39
|
type PiModel = NonNullable<ExtensionContext["model"]>;
|
|
32
40
|
|
|
@@ -34,9 +42,10 @@ export const AUTH_FINGERPRINT_SALT = randomBytes(32);
|
|
|
34
42
|
|
|
35
43
|
export const SUPPORTED_ADAPTERS: readonly UsageProviderAdapter[] = [
|
|
36
44
|
{
|
|
37
|
-
id:
|
|
45
|
+
id: CODEX_PROVIDER_ID,
|
|
38
46
|
displayName: "OpenAI Codex",
|
|
39
|
-
providerIds: [
|
|
47
|
+
providerIds: [CODEX_PROVIDER_ID],
|
|
48
|
+
officialOrigins: ["https://chatgpt.com"],
|
|
40
49
|
semantics: {
|
|
41
50
|
kind: "consumer-subscription",
|
|
42
51
|
label: "ChatGPT subscription limits",
|
|
@@ -58,6 +67,7 @@ export const SUPPORTED_ADAPTERS: readonly UsageProviderAdapter[] = [
|
|
|
58
67
|
id: "opencode-go",
|
|
59
68
|
displayName: "OpenCode Go",
|
|
60
69
|
providerIds: ["opencode-go"],
|
|
70
|
+
officialOrigins: ["https://opencode.ai"],
|
|
61
71
|
semantics: { kind: "consumer-subscription", label: "OpenCode Go plan usage" },
|
|
62
72
|
async query(auth, signal, timeoutMs) {
|
|
63
73
|
return normalizeOpenCodeGoUsage(
|
|
@@ -76,6 +86,7 @@ export const SUPPORTED_ADAPTERS: readonly UsageProviderAdapter[] = [
|
|
|
76
86
|
id: "kimi-coding",
|
|
77
87
|
displayName: "Kimi Coding",
|
|
78
88
|
providerIds: ["kimi-coding"],
|
|
89
|
+
officialOrigins: ["https://api.kimi.com"],
|
|
79
90
|
semantics: { kind: "consumer-subscription", label: "Kimi Coding plan usage" },
|
|
80
91
|
async query(auth, signal, timeoutMs) {
|
|
81
92
|
return normalizeKimiUsage(
|
|
@@ -94,6 +105,7 @@ export const SUPPORTED_ADAPTERS: readonly UsageProviderAdapter[] = [
|
|
|
94
105
|
id: "xai",
|
|
95
106
|
displayName: "Grok",
|
|
96
107
|
providerIds: ["xai", "xai-auth"],
|
|
108
|
+
officialOrigins: ["https://api.x.ai", "https://cli-chat-proxy.grok.com"],
|
|
97
109
|
semantics: {
|
|
98
110
|
kind: "consumer-subscription",
|
|
99
111
|
label: "SuperGrok subscription usage",
|
|
@@ -106,7 +118,7 @@ export const SUPPORTED_ADAPTERS: readonly UsageProviderAdapter[] = [
|
|
|
106
118
|
signal,
|
|
107
119
|
timeoutMs,
|
|
108
120
|
"Grok identity endpoint",
|
|
109
|
-
{ headers:
|
|
121
|
+
{ headers: grokRequestHeaders() },
|
|
110
122
|
);
|
|
111
123
|
const userId = normalizeGrokIdentity(identity);
|
|
112
124
|
const billing = await fetchProviderJson(
|
|
@@ -115,7 +127,7 @@ export const SUPPORTED_ADAPTERS: readonly UsageProviderAdapter[] = [
|
|
|
115
127
|
signal,
|
|
116
128
|
timeoutMs,
|
|
117
129
|
"Grok billing endpoint",
|
|
118
|
-
{ headers:
|
|
130
|
+
{ headers: grokRequestHeaders(userId) },
|
|
119
131
|
);
|
|
120
132
|
return normalizeGrokBilling(billing, Date.now());
|
|
121
133
|
},
|
|
@@ -139,14 +151,14 @@ export async function resolveUsageAuth(
|
|
|
139
151
|
if (
|
|
140
152
|
current &&
|
|
141
153
|
adapter.providerIds.includes(current.provider) &&
|
|
142
|
-
!hasOfficialOrigin(current.baseUrl,
|
|
154
|
+
!hasOfficialOrigin(current.baseUrl, adapter)
|
|
143
155
|
) {
|
|
144
156
|
throw new Error(
|
|
145
157
|
`${adapter.displayName} usage cannot send a custom provider credential to an official usage endpoint.`,
|
|
146
158
|
);
|
|
147
159
|
}
|
|
148
160
|
const candidates = candidateModels(ctx, adapter.providerIds).filter(
|
|
149
|
-
(candidate) => hasOfficialOrigin(candidate.baseUrl,
|
|
161
|
+
(candidate) => hasOfficialOrigin(candidate.baseUrl, adapter),
|
|
150
162
|
);
|
|
151
163
|
const currentModel =
|
|
152
164
|
current && adapter.providerIds.includes(current.provider)
|
|
@@ -166,10 +178,7 @@ export async function resolveUsageAuth(
|
|
|
166
178
|
}
|
|
167
179
|
const result = await ctx.modelRegistry.getProviderAuth(model.provider);
|
|
168
180
|
if (!result) return undefined;
|
|
169
|
-
if (
|
|
170
|
-
result.auth.baseUrl &&
|
|
171
|
-
!hasOfficialOrigin(result.auth.baseUrl, model.provider)
|
|
172
|
-
) {
|
|
181
|
+
if (result.auth.baseUrl && !hasOfficialOrigin(result.auth.baseUrl, adapter)) {
|
|
173
182
|
throw new Error(
|
|
174
183
|
`${adapter.displayName} usage cannot send a proxy-resolved credential to an official usage endpoint.`,
|
|
175
184
|
);
|
|
@@ -232,7 +241,7 @@ export async function fetchProviderJson(
|
|
|
232
241
|
try {
|
|
233
242
|
const headers: Record<string, string> = {
|
|
234
243
|
Accept: "application/json",
|
|
235
|
-
"User-Agent":
|
|
244
|
+
"User-Agent": USER_AGENT,
|
|
236
245
|
...auth.headers,
|
|
237
246
|
...request.headers,
|
|
238
247
|
};
|
|
@@ -348,21 +357,11 @@ function candidateModels(
|
|
|
348
357
|
|
|
349
358
|
function hasOfficialOrigin(
|
|
350
359
|
value: string | undefined,
|
|
351
|
-
|
|
360
|
+
adapter: UsageProviderAdapter,
|
|
352
361
|
): boolean {
|
|
353
362
|
if (!value) return false;
|
|
354
363
|
try {
|
|
355
|
-
|
|
356
|
-
if (providerId === "openai-codex") return origin === "https://chatgpt.com";
|
|
357
|
-
if (providerId === "opencode-go") return origin === "https://opencode.ai";
|
|
358
|
-
if (providerId === "kimi-coding") return origin === "https://api.kimi.com";
|
|
359
|
-
if (providerId === "xai" || providerId === "xai-auth") {
|
|
360
|
-
return (
|
|
361
|
-
origin === "https://api.x.ai" ||
|
|
362
|
-
origin === "https://cli-chat-proxy.grok.com"
|
|
363
|
-
);
|
|
364
|
-
}
|
|
365
|
-
return false;
|
|
364
|
+
return adapter.officialOrigins.includes(new URL(value).origin);
|
|
366
365
|
} catch {
|
|
367
366
|
return false;
|
|
368
367
|
}
|
|
@@ -378,13 +377,3 @@ function headerValue(
|
|
|
378
377
|
)?.[1] ?? undefined
|
|
379
378
|
);
|
|
380
379
|
}
|
|
381
|
-
|
|
382
|
-
function grokHeaders(userId?: string): Record<string, string> {
|
|
383
|
-
return {
|
|
384
|
-
"X-XAI-Token-Auth": "xai-grok-cli",
|
|
385
|
-
"x-grok-client-version": "0.1.0",
|
|
386
|
-
"x-grok-client-mode":
|
|
387
|
-
process.stdin.isTTY && process.stdout.isTTY ? "interactive" : "headless",
|
|
388
|
-
...(userId ? { "x-userid": userId } : {}),
|
|
389
|
-
};
|
|
390
|
-
}
|
package/src/status.ts
CHANGED
|
@@ -51,10 +51,7 @@ export function buildUsageStatusEvent(
|
|
|
51
51
|
model?: UsageModel,
|
|
52
52
|
displayMode: UsageDisplayMode = DEFAULT_USAGE_DISPLAY_MODE,
|
|
53
53
|
): UsageStatusEvent {
|
|
54
|
-
const buckets =
|
|
55
|
-
report.providerId === "openai-codex"
|
|
56
|
-
? bucketsForCodexModel(report, model)
|
|
57
|
-
: report.buckets;
|
|
54
|
+
const buckets = bucketsForModel(report, model);
|
|
58
55
|
const windows = sortUsageBuckets(buckets).flatMap((bucket) => {
|
|
59
56
|
const remainingPercent = usagePercentRemaining(bucket);
|
|
60
57
|
const usedPercent = usagePercentUsed(bucket);
|
|
@@ -175,45 +172,50 @@ function usageWindowRank(bucket: UsageBucket): number {
|
|
|
175
172
|
return 3;
|
|
176
173
|
}
|
|
177
174
|
|
|
178
|
-
function
|
|
175
|
+
function bucketsForModel(
|
|
179
176
|
report: UsageReport,
|
|
180
177
|
model?: UsageModel,
|
|
181
178
|
): UsageBucket[] {
|
|
182
|
-
const
|
|
179
|
+
const hasGroups = report.buckets.some((bucket) => bucket.groupId);
|
|
180
|
+
const hasModelGroups = report.buckets.some(
|
|
181
|
+
(bucket) => bucket.modelKeys && bucket.modelKeys.length > 0,
|
|
182
|
+
);
|
|
183
|
+
if (!hasGroups || (!report.defaultGroupId && !hasModelGroups)) {
|
|
184
|
+
return report.buckets;
|
|
185
|
+
}
|
|
186
|
+
const group = selectUsageGroup(report, model);
|
|
183
187
|
return report.buckets.filter(
|
|
184
188
|
(bucket) => (bucket.groupId ?? bucket.id) === group,
|
|
185
189
|
);
|
|
186
190
|
}
|
|
187
191
|
|
|
188
|
-
function
|
|
192
|
+
function selectUsageGroup(
|
|
189
193
|
report: UsageReport,
|
|
190
194
|
model?: UsageModel,
|
|
191
195
|
): string | undefined {
|
|
192
196
|
const groups = [
|
|
193
197
|
...new Set(report.buckets.map((bucket) => bucket.groupId ?? bucket.id)),
|
|
194
198
|
];
|
|
195
|
-
|
|
196
|
-
|
|
199
|
+
const keys = [model?.id, model?.name]
|
|
200
|
+
.map(normalizeKey)
|
|
201
|
+
.filter((value): value is string => Boolean(value));
|
|
202
|
+
const specificGroups = groups
|
|
203
|
+
.filter((group) => group !== report.defaultGroupId)
|
|
204
|
+
.sort((left, right) => right.length - left.length);
|
|
205
|
+
for (const group of specificGroups) {
|
|
206
|
+
const bucket = report.buckets.find(
|
|
207
|
+
(candidate) => (candidate.groupId ?? candidate.id) === group,
|
|
208
|
+
);
|
|
209
|
+
const candidates = [group, bucket?.groupLabel, ...(bucket?.modelKeys ?? [])]
|
|
197
210
|
.map(normalizeKey)
|
|
198
211
|
.filter((value): value is string => Boolean(value));
|
|
199
|
-
|
|
200
|
-
.
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
const bucket = report.buckets.find(
|
|
204
|
-
(candidate) => (candidate.groupId ?? candidate.id) === group,
|
|
205
|
-
);
|
|
206
|
-
const candidates = [group, bucket?.groupLabel, ...(bucket?.modelKeys ?? [])]
|
|
207
|
-
.map(normalizeKey)
|
|
208
|
-
.filter((value): value is string => Boolean(value));
|
|
209
|
-
if (
|
|
210
|
-
candidates.some((candidate) => keys.some((key) => key.includes(candidate)))
|
|
211
|
-
) {
|
|
212
|
-
return group;
|
|
213
|
-
}
|
|
212
|
+
if (
|
|
213
|
+
candidates.some((candidate) => keys.some((key) => key.includes(candidate)))
|
|
214
|
+
) {
|
|
215
|
+
return group;
|
|
214
216
|
}
|
|
215
217
|
}
|
|
216
|
-
return groups.
|
|
218
|
+
return groups.find((group) => group === report.defaultGroupId) ?? groups[0];
|
|
217
219
|
}
|
|
218
220
|
|
|
219
221
|
function normalizeKey(value: string | undefined): string | undefined {
|
package/src/types.ts
CHANGED
|
@@ -42,6 +42,7 @@ export interface UsageReport {
|
|
|
42
42
|
source: string;
|
|
43
43
|
semantics: UsageSemantics;
|
|
44
44
|
buckets: UsageBucket[];
|
|
45
|
+
defaultGroupId?: string;
|
|
45
46
|
metrics: UsageMetric[];
|
|
46
47
|
notes?: string[];
|
|
47
48
|
}
|
|
@@ -59,6 +60,7 @@ export interface UsageProviderAdapter {
|
|
|
59
60
|
id: string;
|
|
60
61
|
displayName: string;
|
|
61
62
|
providerIds: readonly string[];
|
|
63
|
+
officialOrigins: readonly string[];
|
|
62
64
|
semantics: UsageSemantics;
|
|
63
65
|
requiresOAuth?: boolean;
|
|
64
66
|
query(
|
package/src/usage.ts
CHANGED
|
@@ -31,6 +31,7 @@ import {
|
|
|
31
31
|
resolveCodexResetAuth,
|
|
32
32
|
} from "./codex-resets.ts";
|
|
33
33
|
import { formatProviderState } from "./format.ts";
|
|
34
|
+
import { CODEX_PROVIDER_ID } from "./providers/codex-constants.ts";
|
|
34
35
|
import {
|
|
35
36
|
buildUsageStatusEvent,
|
|
36
37
|
formatUsageStatusline,
|
|
@@ -113,6 +114,7 @@ export default function subscriptionUsage(pi: ExtensionAPI): void {
|
|
|
113
114
|
function scheduleStatusRefresh(
|
|
114
115
|
ctx: ExtensionContext,
|
|
115
116
|
model: UsageModel,
|
|
117
|
+
delayMs = CACHE_TTL_MS,
|
|
116
118
|
): void {
|
|
117
119
|
clearStatusTimer();
|
|
118
120
|
const generation = statusGeneration;
|
|
@@ -120,7 +122,7 @@ export default function subscriptionUsage(pi: ExtensionAPI): void {
|
|
|
120
122
|
statusTimer = undefined;
|
|
121
123
|
if (!sessionActive || generation !== statusGeneration) return;
|
|
122
124
|
startStatusRefresh(ctx, model, true);
|
|
123
|
-
},
|
|
125
|
+
}, delayMs);
|
|
124
126
|
}
|
|
125
127
|
|
|
126
128
|
function publishStatus(
|
|
@@ -336,6 +338,11 @@ export default function subscriptionUsage(pi: ExtensionAPI): void {
|
|
|
336
338
|
const controller = new AbortController();
|
|
337
339
|
statusController = controller;
|
|
338
340
|
activeControllers.add(controller);
|
|
341
|
+
const refreshIsCurrent = (): boolean =>
|
|
342
|
+
sessionActive &&
|
|
343
|
+
generation === statusGeneration &&
|
|
344
|
+
!controller.signal.aborted &&
|
|
345
|
+
modelIdentity(ctx.model) === modelIdentity(model);
|
|
339
346
|
try {
|
|
340
347
|
safeSetStatus(ctx, "usage …");
|
|
341
348
|
const outcome = await queryCurrentState(
|
|
@@ -345,14 +352,28 @@ export default function subscriptionUsage(pi: ExtensionAPI): void {
|
|
|
345
352
|
controller.signal,
|
|
346
353
|
);
|
|
347
354
|
if (
|
|
348
|
-
!
|
|
349
|
-
generation !== statusGeneration ||
|
|
350
|
-
controller.signal.aborted ||
|
|
355
|
+
!refreshIsCurrent() ||
|
|
351
356
|
!(await outcomeStillCurrent(ctx, model, outcome, controller.signal))
|
|
352
357
|
) {
|
|
353
358
|
return;
|
|
354
359
|
}
|
|
355
360
|
publishStatus(ctx, outcome, model, true);
|
|
361
|
+
} catch (error) {
|
|
362
|
+
if (isAbortError(error) || !refreshIsCurrent()) return;
|
|
363
|
+
try {
|
|
364
|
+
emitUnavailableUsage();
|
|
365
|
+
} catch {
|
|
366
|
+
// A status consumer must not stop future refreshes.
|
|
367
|
+
}
|
|
368
|
+
if (!refreshIsCurrent()) return;
|
|
369
|
+
try {
|
|
370
|
+
safeSetStatus(ctx, "usage error");
|
|
371
|
+
} catch {
|
|
372
|
+
// Error reporting must not stop future refreshes.
|
|
373
|
+
}
|
|
374
|
+
if (refreshIsCurrent()) {
|
|
375
|
+
scheduleStatusRefresh(ctx, model, FAILURE_BACKOFF_MS);
|
|
376
|
+
}
|
|
356
377
|
} finally {
|
|
357
378
|
activeControllers.delete(controller);
|
|
358
379
|
if (statusController === controller) statusController = undefined;
|
|
@@ -364,10 +385,8 @@ export default function subscriptionUsage(pi: ExtensionAPI): void {
|
|
|
364
385
|
model: UsageModel | undefined,
|
|
365
386
|
force: boolean,
|
|
366
387
|
): void {
|
|
367
|
-
void refreshCurrentStatus(ctx, model, force).catch((
|
|
368
|
-
|
|
369
|
-
emitUnavailableUsage();
|
|
370
|
-
safeSetStatus(ctx, "usage error");
|
|
388
|
+
void refreshCurrentStatus(ctx, model, force).catch(() => {
|
|
389
|
+
// Unsupported-model cleanup is best effort during UI teardown.
|
|
371
390
|
});
|
|
372
391
|
}
|
|
373
392
|
|
|
@@ -377,7 +396,7 @@ export default function subscriptionUsage(pi: ExtensionAPI): void {
|
|
|
377
396
|
controller: AbortController,
|
|
378
397
|
): Promise<StableCurrent | undefined> {
|
|
379
398
|
if (
|
|
380
|
-
ctx.model?.provider !==
|
|
399
|
+
ctx.model?.provider !== CODEX_PROVIDER_ID ||
|
|
381
400
|
current.outcome.state.status !== "ready"
|
|
382
401
|
) {
|
|
383
402
|
ctx.ui.notify(
|
|
@@ -449,7 +468,7 @@ export default function subscriptionUsage(pi: ExtensionAPI): void {
|
|
|
449
468
|
controller.signal,
|
|
450
469
|
QUERY_TIMEOUT_MS,
|
|
451
470
|
);
|
|
452
|
-
cache.clearProvider(
|
|
471
|
+
cache.clearProvider(CODEX_PROVIDER_ID);
|
|
453
472
|
failureBackoff.clear();
|
|
454
473
|
const refreshed = await queryStableCurrent(ctx, true, controller.signal);
|
|
455
474
|
if (refreshed?.model) {
|
|
@@ -498,7 +517,7 @@ export default function subscriptionUsage(pi: ExtensionAPI): void {
|
|
|
498
517
|
publishStatus(ctx, current.outcome, current.model, sessionActive);
|
|
499
518
|
}
|
|
500
519
|
if (
|
|
501
|
-
ctx.model?.provider !==
|
|
520
|
+
ctx.model?.provider !== CODEX_PROVIDER_ID ||
|
|
502
521
|
current.outcome.state.status !== "ready"
|
|
503
522
|
) {
|
|
504
523
|
return;
|