@specode/pi-subscription-usage 0.2.0 → 0.2.2
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/README.md +2 -2
- package/README.zh-CN.md +2 -2
- 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 +180 -46
- package/src/providers/opencode-go.ts +3 -2
- package/src/query.ts +49 -37
- package/src/status.ts +27 -25
- package/src/types.ts +2 -0
- package/src/usage.ts +30 -11
package/README.md
CHANGED
|
@@ -8,7 +8,7 @@ Supported providers:
|
|
|
8
8
|
|
|
9
9
|
- **OpenAI Codex** — 5-hour and weekly quota, model-specific quota, and confirmed reset-credit redemption.
|
|
10
10
|
- **OpenCode Go** — 5-hour, weekly, and monthly windows.
|
|
11
|
-
- **Grok** — weekly or monthly quota using only Pi's `xai` / `xai-auth` OAuth credentials, with account identity verification.
|
|
11
|
+
- **Grok** — weekly and/or monthly quota using only Pi's `xai` / `xai-auth` OAuth credentials, with account identity verification. Unified SuperGrok billing is read from the default monthly endpoint when `?format=credits` omits window percents. Windows use the same `5h / 1w / 1m` status format as other providers.
|
|
12
12
|
- **Kimi Coding** — 5-hour and weekly windows.
|
|
13
13
|
|
|
14
14
|
The extension does not implement or modify Codex Fast mode and never rewrites model requests.
|
|
@@ -53,7 +53,7 @@ Codex results are grouped by quota domain in this order:
|
|
|
53
53
|
|
|
54
54
|
Windows from different domains are never interleaved. Run `/usage` again whenever you want to refresh; the command does not show refresh, provider-switching, or all-provider menus.
|
|
55
55
|
|
|
56
|
-
The reset menu appears only when Codex reports redeemable reset credits. Grok's current API exposes quota windows and natural reset times, but no verified manual-reset endpoint or reset-credit count, so the extension never invents a reset action.
|
|
56
|
+
The reset menu appears only when Codex reports redeemable reset credits. Grok's current API exposes quota windows and natural reset times, but no verified manual-reset endpoint or reset-credit count, so the extension never invents a reset action. Grok windows still render through the same `/usage` bars and status event as Codex, OpenCode Go, and Kimi.
|
|
57
57
|
|
|
58
58
|
## Configuration
|
|
59
59
|
|
package/README.zh-CN.md
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
|
|
9
9
|
- **OpenAI Codex**:5 小时与每周额度、模型专属额度,以及需要确认的重置次数兑换。
|
|
10
10
|
- **OpenCode Go**:5 小时、每周和每月窗口。
|
|
11
|
-
- **Grok
|
|
11
|
+
- **Grok**:每周和/或每月额度;只使用 Pi 的 `xai` / `xai-auth` OAuth 凭据,并先验证账户身份。统一账单账户在 `?format=credits` 缺少窗口百分比时,会再读取默认的月度账单接口。窗口与其他提供商一样使用 `5h / 1w / 1m` 状态格式。
|
|
12
12
|
- **Kimi Coding**:5 小时和每周窗口。
|
|
13
13
|
|
|
14
14
|
本扩展不实现或修改 Codex Fast 模式,也不会改写模型请求。
|
|
@@ -53,7 +53,7 @@ Codex 结果会按以下额度域分组:
|
|
|
53
53
|
|
|
54
54
|
不同额度域的窗口不会交错。需要刷新时再次运行 `/usage` 即可;命令不会显示刷新、切换提供商或查询所有提供商的菜单。
|
|
55
55
|
|
|
56
|
-
只有当 Codex 返回可兑换的重置次数时,才会显示重置菜单。Grok 当前 API 只公开额度窗口和自然重置时间,没有经过验证的手动重置端点或重置次数,因此本扩展不会虚构重置操作。
|
|
56
|
+
只有当 Codex 返回可兑换的重置次数时,才会显示重置菜单。Grok 当前 API 只公开额度窗口和自然重置时间,没有经过验证的手动重置端点或重置次数,因此本扩展不会虚构重置操作。Grok 窗口仍通过与 Codex、OpenCode Go、Kimi 相同的 `/usage` 进度条和状态事件展示。
|
|
57
57
|
|
|
58
58
|
## 配置
|
|
59
59
|
|
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,20 @@ 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
|
+
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
|
+
}
|
|
9
23
|
|
|
10
24
|
export function normalizeGrokIdentity(payload: unknown): string {
|
|
11
25
|
const userId = asObject(payload)?.userId;
|
|
@@ -22,24 +36,60 @@ export function normalizeGrokIdentity(payload: unknown): string {
|
|
|
22
36
|
return userId;
|
|
23
37
|
}
|
|
24
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
|
+
|
|
25
54
|
export function normalizeGrokBilling(
|
|
26
|
-
|
|
55
|
+
creditsPayload: unknown,
|
|
27
56
|
capturedAt: number,
|
|
57
|
+
monthlyPayload?: unknown | null,
|
|
28
58
|
): UsageReport {
|
|
29
|
-
const
|
|
30
|
-
if (!
|
|
31
|
-
const
|
|
32
|
-
|
|
33
|
-
|
|
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;
|
|
34
73
|
}
|
|
35
|
-
const
|
|
36
|
-
|
|
37
|
-
const
|
|
38
|
-
if (buckets.
|
|
39
|
-
|
|
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("Grok billing endpoint returned no displayable quota window.");
|
|
40
81
|
}
|
|
41
|
-
|
|
42
|
-
const
|
|
82
|
+
|
|
83
|
+
const primaryMetrics = collectMetrics(creditsConfig);
|
|
84
|
+
addAccountMetrics(primaryMetrics, creditsRoot);
|
|
85
|
+
const extraMetrics =
|
|
86
|
+
monthlyConfig && monthlyConfig !== creditsConfig
|
|
87
|
+
? collectMetrics(monthlyConfig)
|
|
88
|
+
: [];
|
|
89
|
+
if (monthlyRoot) addAccountMetrics(extraMetrics, monthlyRoot);
|
|
90
|
+
const metrics = mergeMetrics(primaryMetrics, extraMetrics);
|
|
91
|
+
|
|
92
|
+
return {
|
|
43
93
|
providerId: "xai",
|
|
44
94
|
providerName: "Grok",
|
|
45
95
|
capturedAt,
|
|
@@ -51,38 +101,96 @@ export function normalizeGrokBilling(
|
|
|
51
101
|
buckets,
|
|
52
102
|
metrics,
|
|
53
103
|
};
|
|
54
|
-
if (notes.length > 0) report.notes = notes;
|
|
55
|
-
return report;
|
|
56
104
|
}
|
|
57
105
|
|
|
58
|
-
function
|
|
106
|
+
function readOptionalPayload(
|
|
107
|
+
payload: unknown | null | undefined,
|
|
108
|
+
invalidMessage: string,
|
|
109
|
+
): Record<string, unknown> | undefined {
|
|
110
|
+
if (payload === undefined || payload === null) return undefined;
|
|
111
|
+
const root = asObject(payload);
|
|
112
|
+
if (!root) throw new Error(invalidMessage);
|
|
113
|
+
return root;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function billingConfig(
|
|
117
|
+
payload: unknown,
|
|
118
|
+
invalidConfig: "throw" | "skip" = "throw",
|
|
119
|
+
): Record<string, unknown> | undefined {
|
|
120
|
+
const root = asObject(payload);
|
|
121
|
+
if (!root) return undefined;
|
|
122
|
+
if (root.config === undefined) return undefined;
|
|
123
|
+
const config = asObject(root.config);
|
|
124
|
+
if (!config) {
|
|
125
|
+
if (invalidConfig === "skip") return undefined;
|
|
126
|
+
throw new Error("Grok billing response contained an invalid config object.");
|
|
127
|
+
}
|
|
128
|
+
return config;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function parseCreditsWindow(
|
|
59
132
|
config: Record<string, unknown> | undefined,
|
|
60
133
|
): UsageBucket | undefined {
|
|
61
|
-
|
|
62
|
-
const
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
usedCents !== undefined &&
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
) {
|
|
71
|
-
used = Math.min(100, (usedCents / limitCents) * 100);
|
|
134
|
+
if (!config) return undefined;
|
|
135
|
+
const period = asObject(config.currentPeriod);
|
|
136
|
+
let used = boundedPercent(config.creditUsagePercent);
|
|
137
|
+
if (used === undefined && isWeeklyPeriod(period)) {
|
|
138
|
+
const usedCents = boundedCents(config.used);
|
|
139
|
+
const limitCents = boundedCents(config.monthlyLimit);
|
|
140
|
+
if (usedCents !== undefined && limitCents !== undefined && limitCents > 0) {
|
|
141
|
+
used = Math.min(100, (usedCents / limitCents) * 100);
|
|
142
|
+
}
|
|
72
143
|
}
|
|
73
144
|
if (used === undefined) return undefined;
|
|
74
|
-
|
|
75
|
-
|
|
145
|
+
return percentWindow("weekly", used, config, period, WEEKLY_WINDOW_MINUTES);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function parseMonthlyWindow(
|
|
149
|
+
config: Record<string, unknown> | undefined,
|
|
150
|
+
): UsageBucket | undefined {
|
|
151
|
+
if (!config) return undefined;
|
|
152
|
+
const usedCents = boundedCents(config.used);
|
|
153
|
+
const limitCents = boundedCents(config.monthlyLimit);
|
|
154
|
+
if (usedCents === undefined || limitCents === undefined || limitCents <= 0) {
|
|
155
|
+
return undefined;
|
|
156
|
+
}
|
|
157
|
+
const used = Math.min(100, (usedCents / limitCents) * 100);
|
|
158
|
+
const period = asObject(config.currentPeriod);
|
|
159
|
+
return percentWindow(
|
|
160
|
+
"monthly",
|
|
161
|
+
used,
|
|
162
|
+
config,
|
|
163
|
+
isWeeklyPeriod(period) ? undefined : period,
|
|
164
|
+
MONTHLY_WINDOW_MINUTES,
|
|
165
|
+
);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function percentWindow(
|
|
169
|
+
kind: "weekly" | "monthly",
|
|
170
|
+
used: number,
|
|
171
|
+
config: Record<string, unknown>,
|
|
172
|
+
period: Record<string, unknown> | undefined,
|
|
173
|
+
fallbackMinutes: number,
|
|
174
|
+
): UsageBucket {
|
|
76
175
|
const periodInfo = parseUsagePeriod(config, period);
|
|
77
176
|
const bucket: UsageBucket = {
|
|
78
|
-
id:
|
|
79
|
-
label: "
|
|
177
|
+
id: kind,
|
|
178
|
+
label: kind === "monthly" ? "Monthly window" : "Weekly window",
|
|
80
179
|
used,
|
|
81
180
|
remaining: 100 - used,
|
|
82
181
|
limit: 100,
|
|
83
182
|
unit: "percent",
|
|
84
|
-
|
|
183
|
+
period: kind,
|
|
184
|
+
windowMinutes:
|
|
185
|
+
periodInfo.period === kind
|
|
186
|
+
? (periodInfo.windowMinutes ?? fallbackMinutes)
|
|
187
|
+
: fallbackMinutes,
|
|
85
188
|
};
|
|
189
|
+
const resetsAt = parseTimestamp(
|
|
190
|
+
kind === "monthly"
|
|
191
|
+
? (config.billingPeriodEnd ?? period?.end)
|
|
192
|
+
: (period?.end ?? config.billingPeriodEnd),
|
|
193
|
+
);
|
|
86
194
|
if (resetsAt !== undefined) bucket.resetsAt = resetsAt;
|
|
87
195
|
return bucket;
|
|
88
196
|
}
|
|
@@ -94,10 +202,10 @@ function parseUsagePeriod(
|
|
|
94
202
|
const type = currentPeriod?.type;
|
|
95
203
|
if (typeof type === "string") {
|
|
96
204
|
if (type.toUpperCase().includes("WEEKLY")) {
|
|
97
|
-
return { period: "weekly", windowMinutes:
|
|
205
|
+
return { period: "weekly", windowMinutes: WEEKLY_WINDOW_MINUTES };
|
|
98
206
|
}
|
|
99
207
|
if (type.toUpperCase().includes("MONTHLY")) {
|
|
100
|
-
return { period: "monthly", windowMinutes:
|
|
208
|
+
return { period: "monthly", windowMinutes: MONTHLY_WINDOW_MINUTES };
|
|
101
209
|
}
|
|
102
210
|
}
|
|
103
211
|
const start = parseTimestamp(
|
|
@@ -115,6 +223,14 @@ function parseUsagePeriod(
|
|
|
115
223
|
return { windowMinutes };
|
|
116
224
|
}
|
|
117
225
|
|
|
226
|
+
function isWeeklyPeriod(
|
|
227
|
+
period: Record<string, unknown> | undefined,
|
|
228
|
+
): period is Record<string, unknown> {
|
|
229
|
+
return (
|
|
230
|
+
typeof period?.type === "string" && period.type.toUpperCase().includes("WEEK")
|
|
231
|
+
);
|
|
232
|
+
}
|
|
233
|
+
|
|
118
234
|
function collectMetrics(
|
|
119
235
|
config: Record<string, unknown> | undefined,
|
|
120
236
|
): UsageMetric[] {
|
|
@@ -122,46 +238,64 @@ function collectMetrics(
|
|
|
122
238
|
addUsdMetric(
|
|
123
239
|
metrics,
|
|
124
240
|
"included-used",
|
|
125
|
-
"Included
|
|
241
|
+
"Included Used",
|
|
126
242
|
boundedCents(config?.used),
|
|
127
243
|
);
|
|
128
244
|
addUsdMetric(
|
|
129
245
|
metrics,
|
|
130
246
|
"included-limit",
|
|
131
|
-
"Included
|
|
247
|
+
"Included Total",
|
|
132
248
|
boundedCents(config?.monthlyLimit),
|
|
133
249
|
);
|
|
134
250
|
addUsdMetric(
|
|
135
251
|
metrics,
|
|
136
252
|
"on-demand-used",
|
|
137
|
-
"On-
|
|
253
|
+
"On-Demand Used",
|
|
138
254
|
boundedCents(config?.onDemandUsed),
|
|
139
255
|
);
|
|
140
256
|
addUsdMetric(
|
|
141
257
|
metrics,
|
|
142
258
|
"on-demand-cap",
|
|
143
|
-
"On-
|
|
259
|
+
"On-Demand Cap",
|
|
144
260
|
boundedCents(config?.onDemandCap),
|
|
145
261
|
);
|
|
146
262
|
addUsdMetric(
|
|
147
263
|
metrics,
|
|
148
264
|
"prepaid-balance",
|
|
149
|
-
"Prepaid
|
|
265
|
+
"Prepaid Balance",
|
|
150
266
|
boundedCents(config?.prepaidBalance),
|
|
151
267
|
);
|
|
152
268
|
return metrics;
|
|
153
269
|
}
|
|
154
270
|
|
|
155
|
-
function
|
|
156
|
-
|
|
271
|
+
function addAccountMetrics(
|
|
272
|
+
metrics: UsageMetric[],
|
|
273
|
+
root: Record<string, unknown>,
|
|
274
|
+
): void {
|
|
157
275
|
const tier = boundedLabel(root.subscriptionTier);
|
|
158
|
-
if (tier)
|
|
276
|
+
if (tier) metrics.push({ id: "plan", label: "Plan", value: tier });
|
|
159
277
|
if (typeof root.onDemandEnabled === "boolean") {
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
278
|
+
metrics.push({
|
|
279
|
+
id: "on-demand",
|
|
280
|
+
label: "On-Demand",
|
|
281
|
+
value: root.onDemandEnabled ? "on" : "off",
|
|
282
|
+
});
|
|
163
283
|
}
|
|
164
|
-
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
function mergeMetrics(
|
|
287
|
+
primary: UsageMetric[],
|
|
288
|
+
extra: UsageMetric[],
|
|
289
|
+
): UsageMetric[] {
|
|
290
|
+
const seen = new Set(primary.map((metric) => metric.id));
|
|
291
|
+
return [
|
|
292
|
+
...primary,
|
|
293
|
+
...extra.filter((metric) => {
|
|
294
|
+
if (seen.has(metric.id)) return false;
|
|
295
|
+
seen.add(metric.id);
|
|
296
|
+
return true;
|
|
297
|
+
}),
|
|
298
|
+
];
|
|
165
299
|
}
|
|
166
300
|
|
|
167
301
|
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,15 +1,21 @@
|
|
|
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,
|
|
8
|
+
isAbortError,
|
|
7
9
|
redactUsageError,
|
|
8
10
|
} from "./core.ts";
|
|
11
|
+
import { CODEX_PROVIDER_ID } from "./providers/codex-constants.ts";
|
|
9
12
|
import { normalizeCodexUsage } from "./providers/codex.ts";
|
|
10
13
|
import {
|
|
14
|
+
grokRequestHeaders,
|
|
11
15
|
normalizeGrokBilling,
|
|
12
16
|
normalizeGrokIdentity,
|
|
17
|
+
requiresGrokMonthlyQuota,
|
|
18
|
+
shouldProbeGrokMonthly,
|
|
13
19
|
} from "./providers/grok.ts";
|
|
14
20
|
import { normalizeKimiUsage } from "./providers/kimi.ts";
|
|
15
21
|
import { normalizeOpenCodeGoUsage } from "./providers/opencode-go.ts";
|
|
@@ -23,10 +29,16 @@ const CODEX_USAGE_URL = "https://chatgpt.com/backend-api/wham/usage";
|
|
|
23
29
|
const OPENCODE_GO_USAGE_URL = "https://opencode.ai/zen/go/v1/usage";
|
|
24
30
|
const KIMI_USAGE_URL = "https://api.kimi.com/coding/v1/usages";
|
|
25
31
|
const GROK_USER_URL = "https://cli-chat-proxy.grok.com/v1/user";
|
|
26
|
-
const
|
|
32
|
+
const GROK_CREDITS_URL =
|
|
27
33
|
"https://cli-chat-proxy.grok.com/v1/billing?format=credits";
|
|
34
|
+
const GROK_MONTHLY_URL = "https://cli-chat-proxy.grok.com/v1/billing";
|
|
28
35
|
const MAX_SUCCESS_BODY_BYTES = 64 * 1024;
|
|
29
36
|
const MAX_ERROR_BODY_BYTES = 4 * 1024;
|
|
37
|
+
const PACKAGE_METADATA = createRequire(import.meta.url)("../package.json") as {
|
|
38
|
+
name: string;
|
|
39
|
+
version: string;
|
|
40
|
+
};
|
|
41
|
+
const USER_AGENT = `${PACKAGE_METADATA.name}/${PACKAGE_METADATA.version}`;
|
|
30
42
|
|
|
31
43
|
type PiModel = NonNullable<ExtensionContext["model"]>;
|
|
32
44
|
|
|
@@ -34,9 +46,10 @@ export const AUTH_FINGERPRINT_SALT = randomBytes(32);
|
|
|
34
46
|
|
|
35
47
|
export const SUPPORTED_ADAPTERS: readonly UsageProviderAdapter[] = [
|
|
36
48
|
{
|
|
37
|
-
id:
|
|
49
|
+
id: CODEX_PROVIDER_ID,
|
|
38
50
|
displayName: "OpenAI Codex",
|
|
39
|
-
providerIds: [
|
|
51
|
+
providerIds: [CODEX_PROVIDER_ID],
|
|
52
|
+
officialOrigins: ["https://chatgpt.com"],
|
|
40
53
|
semantics: {
|
|
41
54
|
kind: "consumer-subscription",
|
|
42
55
|
label: "ChatGPT subscription limits",
|
|
@@ -58,6 +71,7 @@ export const SUPPORTED_ADAPTERS: readonly UsageProviderAdapter[] = [
|
|
|
58
71
|
id: "opencode-go",
|
|
59
72
|
displayName: "OpenCode Go",
|
|
60
73
|
providerIds: ["opencode-go"],
|
|
74
|
+
officialOrigins: ["https://opencode.ai"],
|
|
61
75
|
semantics: { kind: "consumer-subscription", label: "OpenCode Go plan usage" },
|
|
62
76
|
async query(auth, signal, timeoutMs) {
|
|
63
77
|
return normalizeOpenCodeGoUsage(
|
|
@@ -76,6 +90,7 @@ export const SUPPORTED_ADAPTERS: readonly UsageProviderAdapter[] = [
|
|
|
76
90
|
id: "kimi-coding",
|
|
77
91
|
displayName: "Kimi Coding",
|
|
78
92
|
providerIds: ["kimi-coding"],
|
|
93
|
+
officialOrigins: ["https://api.kimi.com"],
|
|
79
94
|
semantics: { kind: "consumer-subscription", label: "Kimi Coding plan usage" },
|
|
80
95
|
async query(auth, signal, timeoutMs) {
|
|
81
96
|
return normalizeKimiUsage(
|
|
@@ -94,6 +109,7 @@ export const SUPPORTED_ADAPTERS: readonly UsageProviderAdapter[] = [
|
|
|
94
109
|
id: "xai",
|
|
95
110
|
displayName: "Grok",
|
|
96
111
|
providerIds: ["xai", "xai-auth"],
|
|
112
|
+
officialOrigins: ["https://api.x.ai", "https://cli-chat-proxy.grok.com"],
|
|
97
113
|
semantics: {
|
|
98
114
|
kind: "consumer-subscription",
|
|
99
115
|
label: "SuperGrok subscription usage",
|
|
@@ -106,18 +122,37 @@ export const SUPPORTED_ADAPTERS: readonly UsageProviderAdapter[] = [
|
|
|
106
122
|
signal,
|
|
107
123
|
timeoutMs,
|
|
108
124
|
"Grok identity endpoint",
|
|
109
|
-
{ headers:
|
|
125
|
+
{ headers: grokRequestHeaders() },
|
|
110
126
|
);
|
|
111
127
|
const userId = normalizeGrokIdentity(identity);
|
|
112
|
-
const
|
|
113
|
-
|
|
128
|
+
const request = { headers: grokRequestHeaders(userId) };
|
|
129
|
+
const credits = await fetchProviderJson(
|
|
130
|
+
GROK_CREDITS_URL,
|
|
114
131
|
auth,
|
|
115
132
|
signal,
|
|
116
133
|
timeoutMs,
|
|
117
134
|
"Grok billing endpoint",
|
|
118
|
-
|
|
135
|
+
request,
|
|
119
136
|
);
|
|
120
|
-
|
|
137
|
+
const capturedAt = Date.now();
|
|
138
|
+
const monthlyRequired = requiresGrokMonthlyQuota(credits);
|
|
139
|
+
let monthly: Record<string, unknown> | null | undefined;
|
|
140
|
+
if (shouldProbeGrokMonthly(credits)) {
|
|
141
|
+
try {
|
|
142
|
+
monthly = await fetchProviderJson(
|
|
143
|
+
GROK_MONTHLY_URL,
|
|
144
|
+
auth,
|
|
145
|
+
signal,
|
|
146
|
+
timeoutMs,
|
|
147
|
+
"Grok monthly billing endpoint",
|
|
148
|
+
request,
|
|
149
|
+
);
|
|
150
|
+
} catch (error) {
|
|
151
|
+
if (isAbortError(error) || monthlyRequired) throw error;
|
|
152
|
+
monthly = null;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
return normalizeGrokBilling(credits, capturedAt, monthly);
|
|
121
156
|
},
|
|
122
157
|
},
|
|
123
158
|
];
|
|
@@ -139,14 +174,14 @@ export async function resolveUsageAuth(
|
|
|
139
174
|
if (
|
|
140
175
|
current &&
|
|
141
176
|
adapter.providerIds.includes(current.provider) &&
|
|
142
|
-
!hasOfficialOrigin(current.baseUrl,
|
|
177
|
+
!hasOfficialOrigin(current.baseUrl, adapter)
|
|
143
178
|
) {
|
|
144
179
|
throw new Error(
|
|
145
180
|
`${adapter.displayName} usage cannot send a custom provider credential to an official usage endpoint.`,
|
|
146
181
|
);
|
|
147
182
|
}
|
|
148
183
|
const candidates = candidateModels(ctx, adapter.providerIds).filter(
|
|
149
|
-
(candidate) => hasOfficialOrigin(candidate.baseUrl,
|
|
184
|
+
(candidate) => hasOfficialOrigin(candidate.baseUrl, adapter),
|
|
150
185
|
);
|
|
151
186
|
const currentModel =
|
|
152
187
|
current && adapter.providerIds.includes(current.provider)
|
|
@@ -166,10 +201,7 @@ export async function resolveUsageAuth(
|
|
|
166
201
|
}
|
|
167
202
|
const result = await ctx.modelRegistry.getProviderAuth(model.provider);
|
|
168
203
|
if (!result) return undefined;
|
|
169
|
-
if (
|
|
170
|
-
result.auth.baseUrl &&
|
|
171
|
-
!hasOfficialOrigin(result.auth.baseUrl, model.provider)
|
|
172
|
-
) {
|
|
204
|
+
if (result.auth.baseUrl && !hasOfficialOrigin(result.auth.baseUrl, adapter)) {
|
|
173
205
|
throw new Error(
|
|
174
206
|
`${adapter.displayName} usage cannot send a proxy-resolved credential to an official usage endpoint.`,
|
|
175
207
|
);
|
|
@@ -232,7 +264,7 @@ export async function fetchProviderJson(
|
|
|
232
264
|
try {
|
|
233
265
|
const headers: Record<string, string> = {
|
|
234
266
|
Accept: "application/json",
|
|
235
|
-
"User-Agent":
|
|
267
|
+
"User-Agent": USER_AGENT,
|
|
236
268
|
...auth.headers,
|
|
237
269
|
...request.headers,
|
|
238
270
|
};
|
|
@@ -348,21 +380,11 @@ function candidateModels(
|
|
|
348
380
|
|
|
349
381
|
function hasOfficialOrigin(
|
|
350
382
|
value: string | undefined,
|
|
351
|
-
|
|
383
|
+
adapter: UsageProviderAdapter,
|
|
352
384
|
): boolean {
|
|
353
385
|
if (!value) return false;
|
|
354
386
|
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;
|
|
387
|
+
return adapter.officialOrigins.includes(new URL(value).origin);
|
|
366
388
|
} catch {
|
|
367
389
|
return false;
|
|
368
390
|
}
|
|
@@ -378,13 +400,3 @@ function headerValue(
|
|
|
378
400
|
)?.[1] ?? undefined
|
|
379
401
|
);
|
|
380
402
|
}
|
|
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;
|