@specode/pi-subscription-usage 1.1.1 → 1.3.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/README.md +13 -7
- package/README.zh-CN.md +13 -7
- package/package.json +2 -2
- package/src/codex-reset-core.ts +15 -7
- package/src/codex-resets.ts +19 -5
- package/src/providers/openai.ts +145 -0
- package/src/query.ts +62 -3
- package/src/status.ts +3 -1
- package/src/types.ts +4 -0
- package/src/usage.ts +72 -33
package/README.md
CHANGED
|
@@ -6,6 +6,8 @@ A Pi extension that shows the active account's subscription quota in one consist
|
|
|
6
6
|
|
|
7
7
|
Supported providers:
|
|
8
8
|
|
|
9
|
+
- **OpenAI (ChatGPT subscription)** — separate `Plan limits` and app-limit groups for Pi's `openai` OAuth login, rendered with the existing quota bars. The footer and status event use `Plan limits`, matching the ChatGPT usage page. Also requires `openai-codex` OAuth in Pi for the same ChatGPT account/workspace: its backend credential reads `/wham/usage` for website plan windows (`rate_limit`) and credits, and `/wham/usage/chatpass/apps` for the exact active application registration. Plan and app windows have distinct percentages and reset times; neither substitutes for the other. `App Allowance` is the configured usage cap, not remaining quota. Both credentials participate in cache invalidation. No browser cookies are used. Available account reset tickets are shown as `Account Resets`; redemption uses the companion Codex account's reset endpoint with explicit confirmation, not an app-specific reset endpoint.
|
|
10
|
+
|
|
9
11
|
- **OpenAI Codex** — 5-hour and weekly quota, model-specific quota, and confirmed reset-credit redemption.
|
|
10
12
|
- **OpenCode Go** — 5-hour, weekly, and monthly windows.
|
|
11
13
|
- **Grok** — weekly and/or monthly quota using only Pi's `xai` / `xai-auth` OAuth credentials, with account identity verification. A weekly `currentPeriod` with an omitted `creditUsagePercent` is treated as 0% used (proto3 omits zero after reset). Unified SuperGrok billing is still probed from the default monthly endpoint, but that probe is no longer required when the weekly window is already displayable. Windows use the same `5h / 1w / 1m` status format as other providers.
|
|
@@ -53,7 +55,7 @@ Codex results are grouped by quota domain in this order:
|
|
|
53
55
|
|
|
54
56
|
Windows from different domains are never interleaved. When available, the Codex `Account` section displays the email decoded locally from the active OAuth token. Run `/usage` again whenever you want to refresh; the command does not show refresh, provider-switching, or all-provider menus.
|
|
55
57
|
|
|
56
|
-
The reset menu appears
|
|
58
|
+
The reset menu appears for OpenAI and Codex only when redeemable reset credits are verified. 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
59
|
|
|
58
60
|
## Configuration
|
|
59
61
|
|
|
@@ -72,12 +74,14 @@ Create `~/.pi/agent/subscription-usage.json` for a global setting, or `.pi/subsc
|
|
|
72
74
|
|
|
73
75
|
The setting applies to the footer status, `/usage` quota bars, and the structured status event. Run `/reload` after editing the file.
|
|
74
76
|
|
|
75
|
-
## Codex reset safety
|
|
77
|
+
## OpenAI / Codex reset safety
|
|
78
|
+
|
|
79
|
+
OpenAI mode uses the same `/wham/rate-limit-reset-credits` and `/consume` endpoints as the ChatGPT usage page. Only explicit, available, plan-supported, unexpired `codex_rate_limits` tickets are offered; failed listing never falls back to automatic redemption. Tickets reset server-defined account windows, **not necessarily the current app's window**. The confirmation states this scope. Reset availability failure does not hide plan/app quota; successful redemption invalidates both providers' usage caches.
|
|
76
80
|
|
|
77
|
-
Before redeeming a
|
|
81
|
+
Before redeeming a reset credit, the extension:
|
|
78
82
|
|
|
79
|
-
1. Verifies that the active model
|
|
80
|
-
2. Verifies that the runtime token exactly matches the OAuth account stored by Pi through `/login`.
|
|
83
|
+
1. Verifies that the active OpenAI or Codex model and usage account have not changed.
|
|
84
|
+
2. Verifies that the runtime token exactly matches the OAuth account stored by Pi through `/login`. OpenAI mode checks both stored credentials and rechecks application matching before redemption.
|
|
81
85
|
3. Shows the reset that will be consumed and asks for explicit confirmation. `Cancel (Default)` is always the first option; only deliberately choosing the second option continues.
|
|
82
86
|
4. Uses a unique request ID and reuses it across retries.
|
|
83
87
|
|
|
@@ -93,12 +97,12 @@ Windows are always ordered as `5h / 1w / 1m / other`. Other extensions can consu
|
|
|
93
97
|
## Security boundaries
|
|
94
98
|
|
|
95
99
|
- Usage queries resolve credentials only through `ctx.modelRegistry.getProviderAuth()`.
|
|
96
|
-
-
|
|
100
|
+
- Account reset additionally reads Pi's stored OAuth credentials through the public `readStoredCredential()` API, solely to verify that it exactly matches the active runtime account before redemption.
|
|
97
101
|
- Grok never reads `~/.grok/auth.json` and never accepts an API key in place of subscription OAuth.
|
|
98
102
|
- Credentials are never written to caches, sessions, the status line, or error messages. Cache keys contain only in-process HMAC fingerprints.
|
|
99
103
|
- The Codex email is decoded locally for the `/usage` account panel and is not included in the footer or structured status event.
|
|
100
104
|
- Credentials are sent only to the corresponding official domains. Custom proxies and custom base URLs are rejected.
|
|
101
|
-
-
|
|
105
|
+
- Account reset redemption (OpenAI / Codex) is the only write operation. It is shown only when redeemable credits exist and always requires explicit confirmation.
|
|
102
106
|
|
|
103
107
|
## Development
|
|
104
108
|
|
|
@@ -127,6 +131,8 @@ pi --no-extensions --offline -e ./index.ts --list-models
|
|
|
127
131
|
|
|
128
132
|
## Stability
|
|
129
133
|
|
|
134
|
+
OpenAI app usage also depends on an undocumented ChatGPT endpoint. If the companion Codex login is missing, sign in to **OpenAI Codex** through `/login` without changing the active OpenAI model. An account/workspace mismatch, missing registration, or missing windows produces an error rather than displaying another account's quota. `App Allowance` is the configured share the app may use, not its remaining percentage. `Source` identifies this as the matching app in Pi's Codex account; matching application IDs is not independent cryptographic verification of both token identities.
|
|
135
|
+
|
|
130
136
|
Codex reset, Grok billing, and Kimi usage rely on undocumented provider APIs that may change. When an API fails, the extension reports the query error and does not fall back to uncontrolled credential or proxy paths.
|
|
131
137
|
|
|
132
138
|
## License
|
package/README.zh-CN.md
CHANGED
|
@@ -6,6 +6,8 @@
|
|
|
6
6
|
|
|
7
7
|
支持以下提供商:
|
|
8
8
|
|
|
9
|
+
- **OpenAI(ChatGPT 订阅)**:将套餐 `Plan limits` 与当前应用额度分组展示,沿用原有进度条。底部及状态事件默认展示 `Plan limits`,与 ChatGPT 用量页对齐。同时需要在 Pi 登录同一 ChatGPT 账户/工作区的 `openai-codex`:用其后端凭据从 `/wham/usage` 的 `rate_limit` 读取网页套餐窗口及积分余额,并从 `/wham/usage/chatpass/apps` 精确匹配当前应用窗口。两组各自保留百分比与重置时间,不互相冒充。`App Allowance` 是配置的使用上限,不是剩余额度;任一凭据变化都会使缓存失效。不读取浏览器 Cookie。可用账户重置票据显示为 `Account Resets`;明确确认后,通过配套 Codex 账户的重置接口兑换,并非应用专属重置接口。
|
|
10
|
+
|
|
9
11
|
- **OpenAI Codex**:5 小时与每周额度、模型专属额度,以及需要确认的重置次数兑换。
|
|
10
12
|
- **OpenCode Go**:5 小时、每周和每月窗口。
|
|
11
13
|
- **Grok**:每周和/或每月额度;只使用 Pi 的 `xai` / `xai-auth` OAuth 凭据,并先验证账户身份。若 weekly `currentPeriod` 存在但省略了 `creditUsagePercent`,按已用 0% 处理(proto3 在周期重置后会省略 0)。统一账单账户仍会探测默认月度接口,但 weekly 窗口已经可展示时,月度探测失败不再让整次查询失败。窗口与其他提供商一样使用 `5h / 1w / 1m` 状态格式。
|
|
@@ -53,7 +55,7 @@ Codex 结果会按以下额度域分组:
|
|
|
53
55
|
|
|
54
56
|
不同额度域的窗口不会交错。存在邮箱字段时,Codex `Account` 区域会显示从当前 OAuth Token 本地解析出的邮箱。需要刷新时再次运行 `/usage` 即可;命令不会显示刷新、切换提供商或查询所有提供商的菜单。
|
|
55
57
|
|
|
56
|
-
|
|
58
|
+
OpenAI 和 Codex 模式都仅在确认有可兑换重置次数时显示重置菜单。Grok 当前 API 只公开额度窗口和自然重置时间,没有经过验证的手动重置端点或重置次数,因此本扩展不会虚构重置操作。Grok 窗口仍通过与 Codex、OpenCode Go、Kimi 相同的 `/usage` 进度条和状态事件展示。
|
|
57
59
|
|
|
58
60
|
## 配置
|
|
59
61
|
|
|
@@ -72,12 +74,14 @@ Codex 结果会按以下额度域分组:
|
|
|
72
74
|
|
|
73
75
|
该配置同时作用于底部状态、`/usage` 额度条和结构化状态事件。修改配置文件后运行 `/reload`。
|
|
74
76
|
|
|
75
|
-
## Codex 重置安全措施
|
|
77
|
+
## OpenAI / Codex 重置安全措施
|
|
78
|
+
|
|
79
|
+
OpenAI 模式使用 ChatGPT 用量页相同的 `/wham/rate-limit-reset-credits` 和 `/consume` 接口。只提供明确存在、可用、套餐支持且未过期的 `codex_rate_limits` 票据;列表查询失败时不会退回自动兑换。票据重置的是服务端定义的账户窗口,**不保证清空当前应用窗口**,确认框会说明这一范围。查询重置次数失败不会隐藏套餐和应用额度;兑换成功会使两种模式的额度缓存失效。
|
|
76
80
|
|
|
77
|
-
|
|
81
|
+
兑换重置次数前,本扩展会:
|
|
78
82
|
|
|
79
|
-
1.
|
|
80
|
-
2. 确认运行时令牌与 Pi 通过 `/login` 保存的 OAuth 账户完全一致。
|
|
83
|
+
1. 确认当前 OpenAI 或 Codex 模型及展示额度对应的账户没有变化。
|
|
84
|
+
2. 确认运行时令牌与 Pi 通过 `/login` 保存的 OAuth 账户完全一致。OpenAI 模式会检查两套保存的凭据,并在兑换前重新核验应用匹配。
|
|
81
85
|
3. 显示即将消耗的重置次数并要求明确确认。`Cancel (Default)` 始终位于第一项;只有主动选择第二项才会继续。
|
|
82
86
|
4. 使用唯一请求 ID,并在重试时复用同一个 ID。
|
|
83
87
|
|
|
@@ -93,12 +97,12 @@ Codex 结果会按以下额度域分组:
|
|
|
93
97
|
## 安全边界
|
|
94
98
|
|
|
95
99
|
- 额度查询只通过 `ctx.modelRegistry.getProviderAuth()` 解析凭据。
|
|
96
|
-
-
|
|
100
|
+
- 账户重置还会通过公开的 `readStoredCredential()` API 读取 Pi 保存的 OAuth 凭据,仅用于确认其与当前运行时账户完全一致。
|
|
97
101
|
- Grok 不会读取 `~/.grok/auth.json`,也不会用 API Key 代替订阅 OAuth。
|
|
98
102
|
- 凭据不会写入缓存、会话、状态栏或错误消息;缓存键只保存进程内 HMAC 指纹。
|
|
99
103
|
- Codex 邮箱仅在本地解析后显示于 `/usage` 账户区域,不会进入底部状态或结构化状态事件。
|
|
100
104
|
- 凭据只会发送到对应的官方域名;自定义代理和自定义基础 URL 会被拒绝。
|
|
101
|
-
- Codex
|
|
105
|
+
- 账户重置兑换(OpenAI / Codex)是唯一的写操作。只有存在可兑换次数时才会显示,并且始终要求明确确认。
|
|
102
106
|
|
|
103
107
|
## 开发
|
|
104
108
|
|
|
@@ -127,6 +131,8 @@ pi --no-extensions --offline -e ./index.ts --list-models
|
|
|
127
131
|
|
|
128
132
|
## 稳定性
|
|
129
133
|
|
|
134
|
+
OpenAI 应用额度也依赖未公开的 ChatGPT 接口。缺少配套 Codex 登录时,通过 `/login` 登录 **OpenAI Codex**,无需切换当前 OpenAI 模型。账户/工作区不匹配、找不到应用注册或额度窗口时会报告错误,不展示其他账户的额度。`App Allowance` 表示允许应用使用的套餐份额,不是剩余额度百分比。`Source` 明确标注这是 Pi Codex 登录账户内匹配应用的数据;应用 ID 匹配不是对两套令牌身份的独立验签证明。
|
|
135
|
+
|
|
130
136
|
Codex 重置、Grok 账单和 Kimi 额度依赖未公开的提供商 API,这些 API 可能发生变化。如果 API 调用失败,本扩展只会报告查询错误,不会退回到不受控制的凭据或代理路径。
|
|
131
137
|
|
|
132
138
|
## 许可证
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@specode/pi-subscription-usage",
|
|
3
|
-
"version": "1.
|
|
4
|
-
"description": "Show subscription quota
|
|
3
|
+
"version": "1.3.0",
|
|
4
|
+
"description": "Show subscription quota for OpenAI, Codex, OpenCode Go, Grok, and Kimi, plus OpenAI and Codex account reset credits in Pi",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
7
7
|
"author": "Specode",
|
package/src/codex-reset-core.ts
CHANGED
|
@@ -107,6 +107,7 @@ export function verifyCodexStoredOAuthCredential(
|
|
|
107
107
|
|
|
108
108
|
export function normalizeCodexResetCreditsPayload(
|
|
109
109
|
payload: Record<string, unknown>,
|
|
110
|
+
options: { requireExplicitCredit?: boolean; now?: number } = {},
|
|
110
111
|
): CodexResetAvailability {
|
|
111
112
|
const availableCount = nonnegativeInteger(payload.available_count);
|
|
112
113
|
if (availableCount === undefined) {
|
|
@@ -117,7 +118,7 @@ export function normalizeCodexResetCreditsPayload(
|
|
|
117
118
|
if (payload.credits !== undefined && !Array.isArray(payload.credits)) {
|
|
118
119
|
throw new Error("Codex reset credits response returned invalid credits.");
|
|
119
120
|
}
|
|
120
|
-
const
|
|
121
|
+
const resetOptions: CodexResetOption[] = [];
|
|
121
122
|
for (const rawCredit of payload.credits ?? []) {
|
|
122
123
|
const credit = asObject(rawCredit);
|
|
123
124
|
if (
|
|
@@ -127,17 +128,24 @@ export function normalizeCodexResetCreditsPayload(
|
|
|
127
128
|
) {
|
|
128
129
|
continue;
|
|
129
130
|
}
|
|
130
|
-
options.
|
|
131
|
+
if (options.requireExplicitCredit && credit.is_supported_by_plan !== true) continue;
|
|
132
|
+
const option = normalizeResetOption(credit);
|
|
133
|
+
if (options.requireExplicitCredit && option.expiresAt !== undefined &&
|
|
134
|
+
option.expiresAt * 1_000 <= (options.now ?? Date.now())) continue;
|
|
135
|
+
resetOptions.push(option);
|
|
131
136
|
}
|
|
132
|
-
|
|
137
|
+
resetOptions.sort(
|
|
133
138
|
(left, right) =>
|
|
134
139
|
(left.expiresAt ?? Number.MAX_SAFE_INTEGER) -
|
|
135
140
|
(right.expiresAt ?? Number.MAX_SAFE_INTEGER),
|
|
136
141
|
);
|
|
137
|
-
|
|
138
|
-
if (availableCount > 0 &&
|
|
139
|
-
|
|
140
|
-
return {
|
|
142
|
+
resetOptions.splice(Math.min(availableCount, 32));
|
|
143
|
+
if (!options.requireExplicitCredit && availableCount > 0 && resetOptions.length === 0)
|
|
144
|
+
resetOptions.push(genericCodexResetOption());
|
|
145
|
+
return {
|
|
146
|
+
availableCount: options.requireExplicitCredit ? resetOptions.length : availableCount,
|
|
147
|
+
options: resetOptions,
|
|
148
|
+
};
|
|
141
149
|
}
|
|
142
150
|
|
|
143
151
|
export function parseCodexResetOutcome(
|
package/src/codex-resets.ts
CHANGED
|
@@ -20,6 +20,7 @@ import {
|
|
|
20
20
|
} from "./query.ts";
|
|
21
21
|
import type { ResolvedUsageAuth } from "./types.ts";
|
|
22
22
|
import { CODEX_PROVIDER_ID } from "./providers/codex-constants.ts";
|
|
23
|
+
import { OPENAI_PROVIDER_ID } from "./providers/openai.ts";
|
|
23
24
|
|
|
24
25
|
const RESET_CREDITS_URL =
|
|
25
26
|
"https://chatgpt.com/backend-api/wham/rate-limit-reset-credits";
|
|
@@ -33,13 +34,13 @@ export async function resolveCodexResetAuth(
|
|
|
33
34
|
credentialReader: StoredCredentialReader = readStoredCredential,
|
|
34
35
|
): Promise<ResolvedUsageAuth> {
|
|
35
36
|
const model = ctx.model;
|
|
36
|
-
if (model?.provider !== CODEX_PROVIDER_ID) {
|
|
37
|
+
if (model?.provider !== CODEX_PROVIDER_ID && model?.provider !== OPENAI_PROVIDER_ID) {
|
|
37
38
|
throw new Error(
|
|
38
|
-
"
|
|
39
|
+
"Account resets require the current model to use OpenAI or OpenAI Codex.",
|
|
39
40
|
);
|
|
40
41
|
}
|
|
41
42
|
const expectedModel = `${model.provider}/${model.id}`;
|
|
42
|
-
const adapter = adapterForProvider(
|
|
43
|
+
const adapter = adapterForProvider(model.provider);
|
|
43
44
|
if (!adapter) throw new Error("OpenAI Codex usage support is unavailable.");
|
|
44
45
|
const auth = await resolveUsageAuth(ctx, adapter, salt);
|
|
45
46
|
if (`${ctx.model?.provider}/${ctx.model?.id}` !== expectedModel) {
|
|
@@ -58,16 +59,25 @@ export async function resolveCodexResetAuth(
|
|
|
58
59
|
resolvedAccess,
|
|
59
60
|
credentialReader(CODEX_PROVIDER_ID),
|
|
60
61
|
);
|
|
62
|
+
if (model.provider === OPENAI_PROVIDER_ID) {
|
|
63
|
+
const stored = credentialReader(OPENAI_PROVIDER_ID) as { type?: string; access?: string; refresh?: string } | undefined;
|
|
64
|
+
if (!stored || stored.type !== "oauth" || typeof stored.access !== "string" ||
|
|
65
|
+
typeof stored.refresh !== "string" || !stored.refresh || fingerprintResolvedAuth({ apiKey: `Bearer ${stored.access}`, headers: auth.headers }, salt) !== auth.fingerprint) {
|
|
66
|
+
throw new Error("The active OpenAI runtime account does not match Pi\'s stored OAuth account.");
|
|
67
|
+
}
|
|
68
|
+
}
|
|
61
69
|
const authorization = `Bearer ${resolvedAccess}`;
|
|
62
70
|
const headers = {
|
|
63
71
|
Authorization: authorization,
|
|
64
72
|
"chatgpt-account-id": accountId,
|
|
65
73
|
};
|
|
66
74
|
return {
|
|
67
|
-
actualProviderId:
|
|
75
|
+
actualProviderId: model.provider,
|
|
76
|
+
openaiClientId: auth.openaiClientId,
|
|
77
|
+
usageFingerprint: auth.fingerprint,
|
|
68
78
|
apiKey: resolvedAccess,
|
|
69
79
|
headers,
|
|
70
|
-
fingerprint: fingerprintResolvedAuth({ headers }, salt),
|
|
80
|
+
fingerprint: fingerprintResolvedAuth({ apiKey: auth.fingerprint, headers }, salt),
|
|
71
81
|
secrets: [
|
|
72
82
|
...new Set([...auth.secrets, resolvedAccess, authorization, accountId]),
|
|
73
83
|
],
|
|
@@ -88,6 +98,7 @@ export async function listCodexResetCredits(
|
|
|
88
98
|
timeoutMs,
|
|
89
99
|
"Codex reset endpoint",
|
|
90
100
|
),
|
|
101
|
+
{ requireExplicitCredit: auth.actualProviderId === OPENAI_PROVIDER_ID },
|
|
91
102
|
);
|
|
92
103
|
}
|
|
93
104
|
|
|
@@ -100,6 +111,9 @@ export async function consumeCodexResetCredit(
|
|
|
100
111
|
): Promise<CodexResetOutcome> {
|
|
101
112
|
if (!redeemRequestId)
|
|
102
113
|
throw new Error("Codex reset request ID must not be empty.");
|
|
114
|
+
if (auth.actualProviderId === OPENAI_PROVIDER_ID && !option.creditId) {
|
|
115
|
+
throw new Error("OpenAI account resets require an explicitly selected credit.");
|
|
116
|
+
}
|
|
103
117
|
return parseCodexResetOutcome(
|
|
104
118
|
await fetchProviderJson(
|
|
105
119
|
RESET_CONSUME_URL,
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import { sanitizeDisplayText } from "../core.ts";
|
|
2
|
+
import type { UsageBucket, UsageReport } from "../types.ts";
|
|
3
|
+
import { normalizeCodexUsage } from "./codex.ts";
|
|
4
|
+
|
|
5
|
+
export const OPENAI_PROVIDER_ID = "openai";
|
|
6
|
+
|
|
7
|
+
/** Decode only routing metadata from Pi's active OAuth credential, not identity claims. */
|
|
8
|
+
export function openaiClientIdFromAuthorization(authorization: string): string {
|
|
9
|
+
try {
|
|
10
|
+
const token = /^Bearer\s+(\S+)$/iu.exec(authorization)?.[1];
|
|
11
|
+
const parts = token?.split(".");
|
|
12
|
+
if (parts?.length !== 3) throw new Error();
|
|
13
|
+
const claims = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8"));
|
|
14
|
+
if (
|
|
15
|
+
claims.iss !== "https://auth.openai.com" ||
|
|
16
|
+
claims.aud !== "https://api.openai.com/v1" ||
|
|
17
|
+
typeof claims.scope !== "string" ||
|
|
18
|
+
!claims.scope.split(/\s+/u).includes("chatgpt.tokens.use.direct") ||
|
|
19
|
+
typeof claims.client_id !== "string" ||
|
|
20
|
+
!/^oaiapp_[a-zA-Z0-9_-]+$/u.test(claims.client_id)
|
|
21
|
+
) throw new Error();
|
|
22
|
+
return claims.client_id;
|
|
23
|
+
} catch {
|
|
24
|
+
throw new Error("OpenAI usage requires a Sign in with ChatGPT OAuth credential with an application ID.");
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* The ChatGPT usage page reads app-scoped subscription windows here, separately
|
|
30
|
+
* from Codex's rate_limit. Match the active registration, never an app name or
|
|
31
|
+
* the first result: a different Codex account must not supply another quota.
|
|
32
|
+
*/
|
|
33
|
+
export function normalizeOpenAIUsage(
|
|
34
|
+
payload: unknown,
|
|
35
|
+
clientId: string,
|
|
36
|
+
capturedAt: number,
|
|
37
|
+
): UsageReport {
|
|
38
|
+
const root = asObject(payload);
|
|
39
|
+
const matches = Array.isArray(root?.items)
|
|
40
|
+
? root.items.map(asObject).filter((item) => item?.id === clientId)
|
|
41
|
+
: [];
|
|
42
|
+
if (!clientId || matches.length !== 1) {
|
|
43
|
+
throw new Error("The active OpenAI application was not uniquely found in this Codex account. Sign in to OpenAI and OpenAI Codex with the same ChatGPT account/workspace.");
|
|
44
|
+
}
|
|
45
|
+
const app = matches[0]!;
|
|
46
|
+
const windows = Array.isArray(app.windows) ? app.windows : [];
|
|
47
|
+
const buckets: UsageBucket[] = windows.map((raw, index) => {
|
|
48
|
+
const window = asObject(raw);
|
|
49
|
+
const used = number(window?.used_percent);
|
|
50
|
+
const remaining = number(window?.remaining_percent);
|
|
51
|
+
const seconds = number(window?.limit_window_seconds);
|
|
52
|
+
const reset = number(window?.reset_at);
|
|
53
|
+
if (
|
|
54
|
+
used === undefined || used < 0 || used > 100 ||
|
|
55
|
+
seconds === undefined || seconds <= 0 ||
|
|
56
|
+
(remaining !== undefined && (remaining < 0 || remaining > 100))
|
|
57
|
+
) throw new Error("OpenAI subscription returned an invalid usage window.");
|
|
58
|
+
return {
|
|
59
|
+
id: `chatpass:${index}`,
|
|
60
|
+
label: "App subscription limit",
|
|
61
|
+
used,
|
|
62
|
+
remaining: remaining ?? 100 - used,
|
|
63
|
+
limit: 100,
|
|
64
|
+
unit: "percent",
|
|
65
|
+
windowMinutes: Math.ceil(seconds / 60),
|
|
66
|
+
...(reset !== undefined && reset > 0 ? { resetsAt: reset } : {}),
|
|
67
|
+
};
|
|
68
|
+
});
|
|
69
|
+
if (buckets.length === 0) {
|
|
70
|
+
throw new Error("OpenAI subscription returned no displayable app usage windows.");
|
|
71
|
+
}
|
|
72
|
+
const name = typeof app.name === "string" ? sanitizeDisplayText(app.name, 80) : "";
|
|
73
|
+
const allowance = number(app.allowed_usage_percent);
|
|
74
|
+
return {
|
|
75
|
+
providerId: OPENAI_PROVIDER_ID,
|
|
76
|
+
providerName: "OpenAI (ChatGPT subscription)",
|
|
77
|
+
capturedAt,
|
|
78
|
+
source: "openai-chatpass-pi-auth",
|
|
79
|
+
semantics: { kind: "consumer-subscription", label: "ChatGPT app subscription limits" },
|
|
80
|
+
buckets,
|
|
81
|
+
metrics: [
|
|
82
|
+
{ id: "source", label: "Source", value: "Matched app in Pi Codex account" },
|
|
83
|
+
...(name ? [{ id: "app", label: "App", value: name }] : []),
|
|
84
|
+
...(allowance !== undefined && allowance >= 0 && allowance <= 100
|
|
85
|
+
? [{ id: "allowance", label: "Plan Allowance", value: `${allowance}%` }]
|
|
86
|
+
: []),
|
|
87
|
+
],
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** The website's Plan limits and app-specific caps are separate quota domains. */
|
|
92
|
+
export function normalizeOpenAIPlanUsage(
|
|
93
|
+
appPayload: unknown,
|
|
94
|
+
planPayload: unknown,
|
|
95
|
+
clientId: string,
|
|
96
|
+
capturedAt: number,
|
|
97
|
+
): UsageReport {
|
|
98
|
+
// Require the exact app match even when account-wide plan data is available.
|
|
99
|
+
const app = normalizeOpenAIUsage(appPayload, clientId, capturedAt);
|
|
100
|
+
const root = asObject(planPayload);
|
|
101
|
+
const plan = normalizeCodexUsage({
|
|
102
|
+
rate_limit: root?.rate_limit,
|
|
103
|
+
credits: root?.credits,
|
|
104
|
+
}, capturedAt);
|
|
105
|
+
if (plan.buckets.length === 0) {
|
|
106
|
+
throw new Error("OpenAI subscription returned no displayable plan usage windows.");
|
|
107
|
+
}
|
|
108
|
+
const name = app.metrics.find((metric) => metric.id === "app")?.value ?? "Current";
|
|
109
|
+
return {
|
|
110
|
+
...app,
|
|
111
|
+
source: "openai-plan-and-app-pi-auth",
|
|
112
|
+
semantics: { kind: "consumer-subscription", label: "ChatGPT plan and app limits" },
|
|
113
|
+
defaultGroupId: "chatgpt-plan",
|
|
114
|
+
buckets: [
|
|
115
|
+
...plan.buckets.map((bucket) => ({
|
|
116
|
+
...bucket,
|
|
117
|
+
id: `plan:${bucket.id}`,
|
|
118
|
+
groupId: "chatgpt-plan",
|
|
119
|
+
groupLabel: "Plan limits",
|
|
120
|
+
modelKeys: undefined,
|
|
121
|
+
})),
|
|
122
|
+
...app.buckets.map((bucket) => ({
|
|
123
|
+
...bucket,
|
|
124
|
+
groupId: "chatgpt-app",
|
|
125
|
+
groupLabel: `${name} app limits`,
|
|
126
|
+
})),
|
|
127
|
+
],
|
|
128
|
+
metrics: [
|
|
129
|
+
...app.metrics.map((metric) => metric.id === "allowance"
|
|
130
|
+
? { ...metric, label: "App Allowance" } : metric),
|
|
131
|
+
...plan.metrics.filter((metric) => metric.id === "credits")
|
|
132
|
+
.map((metric) => ({ ...metric, label: "Credits Balance" })),
|
|
133
|
+
],
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function asObject(value: unknown): Record<string, unknown> | undefined {
|
|
138
|
+
return value && typeof value === "object" && !Array.isArray(value)
|
|
139
|
+
? value as Record<string, unknown>
|
|
140
|
+
: undefined;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function number(value: unknown): number | undefined {
|
|
144
|
+
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
|
|
145
|
+
}
|
package/src/query.ts
CHANGED
|
@@ -9,6 +9,7 @@ import {
|
|
|
9
9
|
redactUsageError,
|
|
10
10
|
} from "./core.ts";
|
|
11
11
|
import { CODEX_PROVIDER_ID } from "./providers/codex-constants.ts";
|
|
12
|
+
import { normalizeCodexResetCreditsPayload } from "./codex-reset-core.ts";
|
|
12
13
|
import {
|
|
13
14
|
codexEmailFromAuthorization,
|
|
14
15
|
normalizeCodexUsage,
|
|
@@ -21,6 +22,11 @@ import {
|
|
|
21
22
|
shouldProbeGrokMonthly,
|
|
22
23
|
} from "./providers/grok.ts";
|
|
23
24
|
import { normalizeKimiUsage } from "./providers/kimi.ts";
|
|
25
|
+
import {
|
|
26
|
+
OPENAI_PROVIDER_ID,
|
|
27
|
+
normalizeOpenAIPlanUsage,
|
|
28
|
+
openaiClientIdFromAuthorization,
|
|
29
|
+
} from "./providers/openai.ts";
|
|
24
30
|
import { normalizeOpenCodeGoUsage } from "./providers/opencode-go.ts";
|
|
25
31
|
import type {
|
|
26
32
|
ResolvedUsageAuth,
|
|
@@ -48,6 +54,33 @@ type PiModel = NonNullable<ExtensionContext["model"]>;
|
|
|
48
54
|
export const AUTH_FINGERPRINT_SALT = randomBytes(32);
|
|
49
55
|
|
|
50
56
|
export const SUPPORTED_ADAPTERS: readonly UsageProviderAdapter[] = [
|
|
57
|
+
{
|
|
58
|
+
id: OPENAI_PROVIDER_ID,
|
|
59
|
+
displayName: "OpenAI (ChatGPT subscription)",
|
|
60
|
+
providerIds: [OPENAI_PROVIDER_ID],
|
|
61
|
+
officialOrigins: ["https://api.openai.com"],
|
|
62
|
+
requiresOAuth: true,
|
|
63
|
+
semantics: { kind: "consumer-subscription", label: "ChatGPT plan and app limits" },
|
|
64
|
+
async query(auth, signal, timeoutMs) {
|
|
65
|
+
if (!auth.openaiClientId) throw new Error("OpenAI application identity is unavailable.");
|
|
66
|
+
const [appPayload, planPayload] = await Promise.all([
|
|
67
|
+
fetchProviderJson(`${CODEX_USAGE_URL}/chatpass/apps`, auth, signal, timeoutMs, "OpenAI app usage endpoint"),
|
|
68
|
+
fetchProviderJson(CODEX_USAGE_URL, auth, signal, timeoutMs, "OpenAI plan usage endpoint"),
|
|
69
|
+
]);
|
|
70
|
+
const report = normalizeOpenAIPlanUsage(appPayload, planPayload, auth.openaiClientId, Date.now());
|
|
71
|
+
try {
|
|
72
|
+
const credits = normalizeCodexResetCreditsPayload(await fetchProviderJson(
|
|
73
|
+
"https://chatgpt.com/backend-api/wham/rate-limit-reset-credits",
|
|
74
|
+
auth, signal, timeoutMs, "Account reset credits endpoint",
|
|
75
|
+
), { requireExplicitCredit: true });
|
|
76
|
+
report.metrics.push({ id: "reset-credits", label: "Account Resets", value: credits.availableCount, unit: "count" });
|
|
77
|
+
} catch (error) {
|
|
78
|
+
if (isAbortError(error) || signal.aborted) throw error;
|
|
79
|
+
report.notes = ["Account reset availability could not be verified."];
|
|
80
|
+
}
|
|
81
|
+
return report;
|
|
82
|
+
},
|
|
83
|
+
},
|
|
51
84
|
{
|
|
52
85
|
id: CODEX_PROVIDER_ID,
|
|
53
86
|
displayName: "OpenAI Codex",
|
|
@@ -169,18 +202,26 @@ export function adapterForProvider(
|
|
|
169
202
|
);
|
|
170
203
|
}
|
|
171
204
|
|
|
205
|
+
/** A configured provider mode that does not offer subscription usage. */
|
|
206
|
+
export class UsageUnsupportedError extends Error {
|
|
207
|
+
name = "UsageUnsupportedError";
|
|
208
|
+
}
|
|
209
|
+
|
|
172
210
|
export async function resolveUsageAuth(
|
|
173
211
|
ctx: ExtensionContext,
|
|
174
212
|
adapter: UsageProviderAdapter,
|
|
175
213
|
salt: Uint8Array = AUTH_FINGERPRINT_SALT,
|
|
176
214
|
): Promise<ResolvedUsageAuth | undefined> {
|
|
177
215
|
const current = ctx.model;
|
|
216
|
+
const UnsupportedModeError = adapter.id === OPENAI_PROVIDER_ID
|
|
217
|
+
? UsageUnsupportedError
|
|
218
|
+
: Error;
|
|
178
219
|
if (
|
|
179
220
|
current &&
|
|
180
221
|
adapter.providerIds.includes(current.provider) &&
|
|
181
222
|
!hasOfficialOrigin(current.baseUrl, adapter)
|
|
182
223
|
) {
|
|
183
|
-
throw new
|
|
224
|
+
throw new UnsupportedModeError(
|
|
184
225
|
`${adapter.displayName} usage cannot send a custom provider credential to an official usage endpoint.`,
|
|
185
226
|
);
|
|
186
227
|
}
|
|
@@ -199,14 +240,14 @@ export async function resolveUsageAuth(
|
|
|
199
240
|
);
|
|
200
241
|
if (!model) return undefined;
|
|
201
242
|
if (adapter.requiresOAuth && !ctx.modelRegistry.isUsingOAuth(model)) {
|
|
202
|
-
throw new
|
|
243
|
+
throw new UnsupportedModeError(
|
|
203
244
|
`${adapter.displayName} usage requires Pi OAuth; API-key auth is not accepted.`,
|
|
204
245
|
);
|
|
205
246
|
}
|
|
206
247
|
const result = await ctx.modelRegistry.getProviderAuth(model.provider);
|
|
207
248
|
if (!result) return undefined;
|
|
208
249
|
if (result.auth.baseUrl && !hasOfficialOrigin(result.auth.baseUrl, adapter)) {
|
|
209
|
-
throw new
|
|
250
|
+
throw new UnsupportedModeError(
|
|
210
251
|
`${adapter.displayName} usage cannot send a proxy-resolved credential to an official usage endpoint.`,
|
|
211
252
|
);
|
|
212
253
|
}
|
|
@@ -220,6 +261,24 @@ export async function resolveUsageAuth(
|
|
|
220
261
|
headerValue(result.auth.headers, "Authorization"),
|
|
221
262
|
authorization,
|
|
222
263
|
].filter((value): value is string => Boolean(value));
|
|
264
|
+
if (adapter.id === OPENAI_PROVIDER_ID) {
|
|
265
|
+
const clientId = openaiClientIdFromAuthorization(authorization);
|
|
266
|
+
const codexAdapter = adapterForProvider(CODEX_PROVIDER_ID)!;
|
|
267
|
+
const companion = await resolveUsageAuth(ctx, { ...codexAdapter, requiresOAuth: true }, salt);
|
|
268
|
+
if (!companion) {
|
|
269
|
+
throw new Error("OpenAI app usage also requires OpenAI Codex OAuth in Pi for the same ChatGPT account/workspace. Run /login for OpenAI Codex; keep OpenAI as the active model.");
|
|
270
|
+
}
|
|
271
|
+
return {
|
|
272
|
+
actualProviderId: model.provider,
|
|
273
|
+
model,
|
|
274
|
+
openaiClientId: clientId,
|
|
275
|
+
// Only the backend credential is sent to ChatGPT. The active API token
|
|
276
|
+
// is used locally for registration matching and cache invalidation.
|
|
277
|
+
headers: companion.headers,
|
|
278
|
+
fingerprint: fingerprintResolvedAuth({ apiKey: authorization, headers: companion.headers }, salt),
|
|
279
|
+
secrets: [...secrets, ...companion.secrets, clientId],
|
|
280
|
+
};
|
|
281
|
+
}
|
|
223
282
|
return {
|
|
224
283
|
actualProviderId: model.provider,
|
|
225
284
|
apiKey: result.auth.apiKey,
|
package/src/status.ts
CHANGED
|
@@ -208,7 +208,9 @@ function bucketsForModel(
|
|
|
208
208
|
if (!hasGroups || (!report.defaultGroupId && !hasModelGroups)) {
|
|
209
209
|
return report.buckets;
|
|
210
210
|
}
|
|
211
|
-
const group =
|
|
211
|
+
const group = !hasModelGroups && report.defaultGroupId
|
|
212
|
+
? report.defaultGroupId
|
|
213
|
+
: selectUsageGroup(report, model);
|
|
212
214
|
return report.buckets.filter(
|
|
213
215
|
(bucket) => (bucket.groupId ?? bucket.id) === group,
|
|
214
216
|
);
|
package/src/types.ts
CHANGED
|
@@ -49,6 +49,10 @@ export interface UsageReport {
|
|
|
49
49
|
|
|
50
50
|
export interface ResolvedUsageAuth {
|
|
51
51
|
actualProviderId: string;
|
|
52
|
+
/** Active OpenAI OAuth registration, matched against the ChatGPT app list. */
|
|
53
|
+
openaiClientId?: string;
|
|
54
|
+
/** Original usage identity, retained when reset auth adds account headers. */
|
|
55
|
+
usageFingerprint?: string;
|
|
52
56
|
apiKey?: string;
|
|
53
57
|
headers: Record<string, string>;
|
|
54
58
|
fingerprint: string;
|
package/src/usage.ts
CHANGED
|
@@ -32,6 +32,7 @@ import {
|
|
|
32
32
|
} from "./codex-resets.ts";
|
|
33
33
|
import { formatProviderState } from "./format.ts";
|
|
34
34
|
import { CODEX_PROVIDER_ID } from "./providers/codex-constants.ts";
|
|
35
|
+
import { OPENAI_PROVIDER_ID } from "./providers/openai.ts";
|
|
35
36
|
import {
|
|
36
37
|
buildUsageStatusEvent,
|
|
37
38
|
formatUsageStatusline,
|
|
@@ -43,6 +44,7 @@ import {
|
|
|
43
44
|
adapterForProvider,
|
|
44
45
|
queryProviderUsage,
|
|
45
46
|
resolveUsageAuth,
|
|
47
|
+
UsageUnsupportedError,
|
|
46
48
|
} from "./query.ts";
|
|
47
49
|
import type {
|
|
48
50
|
ProviderUsageState,
|
|
@@ -187,7 +189,9 @@ export default function subscriptionUsage(pi: ExtensionAPI): void {
|
|
|
187
189
|
state: {
|
|
188
190
|
providerId: adapter.id,
|
|
189
191
|
providerName: adapter.displayName,
|
|
190
|
-
status:
|
|
192
|
+
status: error instanceof UsageUnsupportedError
|
|
193
|
+
? "unsupported"
|
|
194
|
+
: "auth-unavailable",
|
|
191
195
|
message: errorMessage(error),
|
|
192
196
|
},
|
|
193
197
|
};
|
|
@@ -402,15 +406,19 @@ export default function subscriptionUsage(pi: ExtensionAPI): void {
|
|
|
402
406
|
controller: AbortController,
|
|
403
407
|
): Promise<StableCurrent | undefined> {
|
|
404
408
|
if (
|
|
405
|
-
ctx.model?.provider
|
|
409
|
+
![CODEX_PROVIDER_ID, OPENAI_PROVIDER_ID].includes(ctx.model?.provider ?? "") ||
|
|
406
410
|
current.outcome.state.status !== "ready"
|
|
407
411
|
) {
|
|
408
412
|
ctx.ui.notify(
|
|
409
|
-
"
|
|
413
|
+
"Account resets require the current OpenAI or Codex OAuth account.",
|
|
410
414
|
"warning",
|
|
411
415
|
);
|
|
412
416
|
return undefined;
|
|
413
417
|
}
|
|
418
|
+
const expectedModel = modelIdentity(current.model);
|
|
419
|
+
const isOpenAI = current.model?.provider === OPENAI_PROVIDER_ID;
|
|
420
|
+
const resetLabel = isOpenAI ? "Account" : "Codex";
|
|
421
|
+
if (modelIdentity(ctx.model) !== expectedModel) throw new Error("Model changed; reset cancelled.");
|
|
414
422
|
const summaryCount = codexResetCount(current.outcome.state.report) ?? 0;
|
|
415
423
|
let auth = await awaitWithDeadline(
|
|
416
424
|
() => resolveCodexResetAuth(ctx),
|
|
@@ -418,6 +426,9 @@ export default function subscriptionUsage(pi: ExtensionAPI): void {
|
|
|
418
426
|
QUERY_TIMEOUT_MS,
|
|
419
427
|
"resolving Codex reset authentication",
|
|
420
428
|
);
|
|
429
|
+
if (auth.usageFingerprint !== current.outcome.fingerprint) {
|
|
430
|
+
throw new Error("Account changed since usage was displayed; run /usage again.");
|
|
431
|
+
}
|
|
421
432
|
let availability;
|
|
422
433
|
try {
|
|
423
434
|
availability = await listCodexResetCredits(
|
|
@@ -426,7 +437,7 @@ export default function subscriptionUsage(pi: ExtensionAPI): void {
|
|
|
426
437
|
QUERY_TIMEOUT_MS,
|
|
427
438
|
);
|
|
428
439
|
} catch (error) {
|
|
429
|
-
if (summaryCount <= 0) throw error;
|
|
440
|
+
if (isOpenAI || isAbortError(error) || summaryCount <= 0) throw error;
|
|
430
441
|
availability = {
|
|
431
442
|
availableCount: summaryCount,
|
|
432
443
|
options: [genericCodexResetOption()],
|
|
@@ -440,52 +451,59 @@ export default function subscriptionUsage(pi: ExtensionAPI): void {
|
|
|
440
451
|
(option: CodexResetOption, index: number) =>
|
|
441
452
|
`${index + 1}. ${option.title} · ${resetOptionExpiration(option)}`,
|
|
442
453
|
);
|
|
443
|
-
const selected = await ctx.ui.select(
|
|
454
|
+
const selected = await ctx.ui.select(`Choose a ${resetLabel} Reset`, labels);
|
|
444
455
|
if (!selected) return undefined;
|
|
445
456
|
const option = availability.options[labels.indexOf(selected)];
|
|
446
457
|
if (!option) return undefined;
|
|
447
458
|
const confirmation = await ctx.ui.select(
|
|
448
|
-
`Redeem one
|
|
459
|
+
`Redeem one ${resetLabel} reset?\n${option.title}\n${option.description}\n${resetOptionExpiration(option)}${isOpenAI ? "\nConsumes a reset from the companion Codex account. Only ticket-supported account windows are reset; clearing this app's quota is not guaranteed." : ""}`,
|
|
449
460
|
[...CODEX_RESET_CONFIRMATION_OPTIONS],
|
|
450
461
|
);
|
|
451
462
|
if (!isCodexResetConfirmed(confirmation)) return undefined;
|
|
452
463
|
|
|
453
|
-
const expectedModel = modelIdentity(ctx.model);
|
|
454
464
|
const expectedFingerprint = auth.fingerprint;
|
|
455
465
|
const requestId = randomUUID();
|
|
466
|
+
let submitted = false;
|
|
456
467
|
while (!controller.signal.aborted) {
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
+
try {
|
|
469
|
+
auth = await awaitWithDeadline(
|
|
470
|
+
() => resolveCodexResetAuth(ctx),
|
|
471
|
+
controller.signal,
|
|
472
|
+
QUERY_TIMEOUT_MS,
|
|
473
|
+
"revalidating Codex reset authentication",
|
|
474
|
+
);
|
|
475
|
+
if (
|
|
476
|
+
modelIdentity(ctx.model) !== expectedModel ||
|
|
477
|
+
auth.fingerprint !== expectedFingerprint
|
|
478
|
+
) {
|
|
479
|
+
throw new Error("Model or account changed; reset not submitted.");
|
|
480
|
+
}
|
|
481
|
+
if (isOpenAI) {
|
|
482
|
+
await queryProviderUsage(adapterForProvider(OPENAI_PROVIDER_ID)!, auth, controller.signal, QUERY_TIMEOUT_MS);
|
|
483
|
+
const checked = await awaitWithDeadline(() => resolveCodexResetAuth(ctx), controller.signal, QUERY_TIMEOUT_MS, "revalidating account reset authentication");
|
|
484
|
+
if (checked.fingerprint !== expectedFingerprint || modelIdentity(ctx.model) !== expectedModel) {
|
|
485
|
+
throw new Error("OpenAI or Codex account changed; reset not submitted.");
|
|
486
|
+
}
|
|
487
|
+
auth = checked;
|
|
488
|
+
}
|
|
489
|
+
} catch (error) {
|
|
490
|
+
if (isAbortError(error) || !sessionActive) throw error;
|
|
491
|
+
if (!submitted) throw error;
|
|
492
|
+
// A previous POST may have succeeded even though its response was lost.
|
|
493
|
+
ctx.ui.notify("Reset result uncertain; retry stopped during account or usage verification. Run /usage to check your quota and reset credits.", "warning");
|
|
494
|
+
return undefined;
|
|
468
495
|
}
|
|
496
|
+
|
|
497
|
+
let outcome;
|
|
469
498
|
try {
|
|
470
|
-
|
|
499
|
+
submitted = true;
|
|
500
|
+
outcome = await consumeCodexResetCredit(
|
|
471
501
|
auth,
|
|
472
502
|
option,
|
|
473
503
|
requestId,
|
|
474
504
|
controller.signal,
|
|
475
505
|
QUERY_TIMEOUT_MS,
|
|
476
506
|
);
|
|
477
|
-
cache.clearProvider(CODEX_PROVIDER_ID);
|
|
478
|
-
failureBackoff.clear();
|
|
479
|
-
const refreshed = await queryStableCurrent(ctx, true, controller.signal);
|
|
480
|
-
if (refreshed?.model) {
|
|
481
|
-
publishStatus(ctx, refreshed.outcome, refreshed.model, sessionActive);
|
|
482
|
-
}
|
|
483
|
-
const remaining =
|
|
484
|
-
refreshed?.outcome.state.status === "ready"
|
|
485
|
-
? codexResetCount(refreshed.outcome.state.report)
|
|
486
|
-
: undefined;
|
|
487
|
-
ctx.ui.notify(formatCodexResetOutcome(outcome, remaining), "info");
|
|
488
|
-
return refreshed;
|
|
489
507
|
} catch (error) {
|
|
490
508
|
if (isAbortError(error) || !sessionActive) throw error;
|
|
491
509
|
const retryAction = "Retry with Same Request ID";
|
|
@@ -494,9 +512,30 @@ export default function subscriptionUsage(pi: ExtensionAPI): void {
|
|
|
494
512
|
"Cancel",
|
|
495
513
|
]);
|
|
496
514
|
if (retry !== retryAction) {
|
|
497
|
-
ctx.ui.notify(`Reset
|
|
515
|
+
ctx.ui.notify(`Reset result uncertain; run /usage to check your quota and reset credits. ${errorMessage(error)}`, "warning");
|
|
498
516
|
return undefined;
|
|
499
517
|
}
|
|
518
|
+
continue;
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
// A confirmed consume result must never become another consume retry.
|
|
522
|
+
cache.clearProvider(CODEX_PROVIDER_ID);
|
|
523
|
+
cache.clearProvider(OPENAI_PROVIDER_ID);
|
|
524
|
+
failureBackoff.clear();
|
|
525
|
+
ctx.ui.notify(formatCodexResetOutcome(outcome, undefined), "info");
|
|
526
|
+
try {
|
|
527
|
+
const refreshed = await queryStableCurrent(ctx, true, controller.signal);
|
|
528
|
+
if (!refreshed || refreshed.outcome.state.status !== "ready") {
|
|
529
|
+
ctx.ui.notify("Reset result confirmed, but usage refresh failed. Run /usage again.", "warning");
|
|
530
|
+
}
|
|
531
|
+
if (refreshed?.model) {
|
|
532
|
+
publishStatus(ctx, refreshed.outcome, refreshed.model, sessionActive);
|
|
533
|
+
}
|
|
534
|
+
return refreshed;
|
|
535
|
+
} catch (error) {
|
|
536
|
+
if (isAbortError(error) || !sessionActive) throw error;
|
|
537
|
+
ctx.ui.notify("Reset result confirmed, but usage refresh or display failed. Run /usage again.", "warning");
|
|
538
|
+
return undefined;
|
|
500
539
|
}
|
|
501
540
|
}
|
|
502
541
|
return undefined;
|
|
@@ -523,7 +562,7 @@ export default function subscriptionUsage(pi: ExtensionAPI): void {
|
|
|
523
562
|
publishStatus(ctx, current.outcome, current.model, sessionActive);
|
|
524
563
|
}
|
|
525
564
|
if (
|
|
526
|
-
ctx.model?.provider
|
|
565
|
+
![CODEX_PROVIDER_ID, OPENAI_PROVIDER_ID].includes(ctx.model?.provider ?? "") ||
|
|
527
566
|
current.outcome.state.status !== "ready"
|
|
528
567
|
) {
|
|
529
568
|
return;
|