@specode/pi-subscription-usage 1.2.0 → 1.3.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/README.md +12 -10
- package/README.zh-CN.md +12 -10
- package/package.json +2 -2
- package/src/codex-reset-core.ts +15 -15
- package/src/codex-resets.ts +22 -9
- package/src/providers/openai.ts +47 -0
- package/src/query.ts +68 -16
- package/src/status.ts +3 -1
- package/src/types.ts +2 -0
- package/src/usage.ts +77 -48
package/README.md
CHANGED
|
@@ -6,9 +6,9 @@ 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)** — app-
|
|
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, because OpenAI rejects the Sign in with ChatGPT token on ChatGPT usage and reset endpoints; run `/login openai-codex` once and keep OpenAI as the active model (see [Stability](#stability)). The Codex 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
10
|
|
|
11
|
-
- **OpenAI Codex** — 5-hour and weekly quota, model-specific quota, and confirmed reset-credit redemption.
|
|
11
|
+
- **OpenAI Codex** — 5-hour and weekly quota, model-specific quota, and confirmed reset-credit redemption. `Resets Left` counts only redeemable tickets from the reset-credit list, not the usage summary.
|
|
12
12
|
- **OpenCode Go** — 5-hour, weekly, and monthly windows.
|
|
13
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.
|
|
14
14
|
- **Kimi Coding** — 5-hour and weekly windows, plus the membership plan reported by the usage API.
|
|
@@ -55,7 +55,7 @@ Codex results are grouped by quota domain in this order:
|
|
|
55
55
|
|
|
56
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.
|
|
57
57
|
|
|
58
|
-
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.
|
|
59
59
|
|
|
60
60
|
## Configuration
|
|
61
61
|
|
|
@@ -74,12 +74,14 @@ Create `~/.pi/agent/subscription-usage.json` for a global setting, or `.pi/subsc
|
|
|
74
74
|
|
|
75
75
|
The setting applies to the footer status, `/usage` quota bars, and the structured status event. Run `/reload` after editing the file.
|
|
76
76
|
|
|
77
|
-
## Codex reset safety
|
|
77
|
+
## OpenAI / Codex reset safety
|
|
78
78
|
|
|
79
|
-
|
|
79
|
+
OpenAI and Codex modes both use the same `/wham/rate-limit-reset-credits` and `/consume` endpoints as the ChatGPT usage page, authenticated with the Codex account's backend credential and scoped to that token's own account (`chatgpt-account-id`) for both display and redemption. Both modes count and offer only explicit, available, plan-supported, unexpired `codex_rate_limits` tickets, and always redeem a specific ticket: neither a summary count nor a failed listing falls back to a server-chosen reset. In OpenAI mode, tickets reset server-defined account windows, **not necessarily the current app's window**; the confirmation states this scope. Reset availability failure does not hide quota; successful redemption invalidates both providers' usage caches.
|
|
80
80
|
|
|
81
|
-
|
|
82
|
-
|
|
81
|
+
Before redeeming a reset credit, the extension:
|
|
82
|
+
|
|
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.
|
|
83
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.
|
|
84
86
|
4. Uses a unique request ID and reuses it across retries.
|
|
85
87
|
|
|
@@ -95,12 +97,12 @@ Windows are always ordered as `5h / 1w / 1m / other`. Other extensions can consu
|
|
|
95
97
|
## Security boundaries
|
|
96
98
|
|
|
97
99
|
- Usage queries resolve credentials only through `ctx.modelRegistry.getProviderAuth()`.
|
|
98
|
-
-
|
|
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.
|
|
99
101
|
- Grok never reads `~/.grok/auth.json` and never accepts an API key in place of subscription OAuth.
|
|
100
102
|
- Credentials are never written to caches, sessions, the status line, or error messages. Cache keys contain only in-process HMAC fingerprints.
|
|
101
103
|
- The Codex email is decoded locally for the `/usage` account panel and is not included in the footer or structured status event.
|
|
102
104
|
- Credentials are sent only to the corresponding official domains. Custom proxies and custom base URLs are rejected.
|
|
103
|
-
-
|
|
105
|
+
- Account reset redemption (OpenAI / Codex) is the only write operation. It is shown only when redeemable credits exist and always requires explicit confirmation.
|
|
104
106
|
|
|
105
107
|
## Development
|
|
106
108
|
|
|
@@ -129,7 +131,7 @@ pi --no-extensions --offline -e ./index.ts --list-models
|
|
|
129
131
|
|
|
130
132
|
## Stability
|
|
131
133
|
|
|
132
|
-
OpenAI app usage also depends on an undocumented ChatGPT endpoint.
|
|
134
|
+
OpenAI app usage also depends on an undocumented ChatGPT endpoint. OpenAI rejects Sign in with ChatGPT tokens on these ChatGPT usage and reset endpoints (HTTP 401), so the companion Codex login is required: run `/login openai-codex` once with the same account/workspace. It is used only to read usage; keep OpenAI as the active model. Without it, check usage at https://chatgpt.com/settings/usage. 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.
|
|
133
135
|
|
|
134
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.
|
|
135
137
|
|
package/README.zh-CN.md
CHANGED
|
@@ -6,9 +6,9 @@
|
|
|
6
6
|
|
|
7
7
|
支持以下提供商:
|
|
8
8
|
|
|
9
|
-
- **OpenAI(ChatGPT
|
|
9
|
+
- **OpenAI(ChatGPT 订阅)**:将套餐 `Plan limits` 与当前应用额度分组展示,沿用原有进度条。底部及状态事件默认展示 `Plan limits`,与 ChatGPT 用量页对齐。同时需要在 Pi 登录同一 ChatGPT 账户/工作区的 `openai-codex`,因为 OpenAI 会拒绝 Sign in with ChatGPT 令牌访问 ChatGPT 用量和重置接口;执行一次 `/login openai-codex` 即可,当前模型仍保持 OpenAI(见[稳定性](#稳定性))。插件用 Codex 后端凭据从 `/wham/usage` 的 `rate_limit` 读取网页套餐窗口及积分余额,并从 `/wham/usage/chatpass/apps` 精确匹配当前应用窗口。两组各自保留百分比与重置时间,不互相冒充。`App Allowance` 是配置的使用上限,不是剩余额度;任一凭据变化都会使缓存失效。不读取浏览器 Cookie。可用账户重置票据显示为 `Account Resets`;明确确认后,通过配套 Codex 账户的重置接口兑换,并非应用专属重置接口。
|
|
10
10
|
|
|
11
|
-
- **OpenAI Codex**:5
|
|
11
|
+
- **OpenAI Codex**:5 小时与每周额度、模型专属额度,以及需要确认的重置次数兑换。`Resets Left` 只统计重置票据列表中可兑换的票据,不采用用量接口的汇总数。
|
|
12
12
|
- **OpenCode Go**:5 小时、每周和每月窗口。
|
|
13
13
|
- **Grok**:每周和/或每月额度;只使用 Pi 的 `xai` / `xai-auth` OAuth 凭据,并先验证账户身份。若 weekly `currentPeriod` 存在但省略了 `creditUsagePercent`,按已用 0% 处理(proto3 在周期重置后会省略 0)。统一账单账户仍会探测默认月度接口,但 weekly 窗口已经可展示时,月度探测失败不再让整次查询失败。窗口与其他提供商一样使用 `5h / 1w / 1m` 状态格式。
|
|
14
14
|
- **Kimi Coding**:5 小时和每周窗口,以及额度接口返回的会员套餐。
|
|
@@ -55,7 +55,7 @@ Codex 结果会按以下额度域分组:
|
|
|
55
55
|
|
|
56
56
|
不同额度域的窗口不会交错。存在邮箱字段时,Codex `Account` 区域会显示从当前 OAuth Token 本地解析出的邮箱。需要刷新时再次运行 `/usage` 即可;命令不会显示刷新、切换提供商或查询所有提供商的菜单。
|
|
57
57
|
|
|
58
|
-
|
|
58
|
+
OpenAI 和 Codex 模式都仅在确认有可兑换重置次数时显示重置菜单。Grok 当前 API 只公开额度窗口和自然重置时间,没有经过验证的手动重置端点或重置次数,因此本扩展不会虚构重置操作。Grok 窗口仍通过与 Codex、OpenCode Go、Kimi 相同的 `/usage` 进度条和状态事件展示。
|
|
59
59
|
|
|
60
60
|
## 配置
|
|
61
61
|
|
|
@@ -74,12 +74,14 @@ Codex 结果会按以下额度域分组:
|
|
|
74
74
|
|
|
75
75
|
该配置同时作用于底部状态、`/usage` 额度条和结构化状态事件。修改配置文件后运行 `/reload`。
|
|
76
76
|
|
|
77
|
-
## Codex 重置安全措施
|
|
77
|
+
## OpenAI / Codex 重置安全措施
|
|
78
78
|
|
|
79
|
-
|
|
79
|
+
OpenAI 与 Codex 模式都使用 ChatGPT 用量页相同的 `/wham/rate-limit-reset-credits` 和 `/consume` 接口,并以 Codex 账户的后端凭据认证;显示和兑换时都通过 `chatgpt-account-id` 限定为该令牌自身的账户。两种模式都只统计和提供明确存在、可用、套餐支持且未过期的 `codex_rate_limits` 票据,且始终指定具体票据兑换:仅有汇总次数或列表查询失败时,都不会退回由服务端选票的兑换。OpenAI 模式下,票据重置的是服务端定义的账户窗口,**不保证清空当前应用窗口**,确认框会说明这一范围。查询重置次数失败不会隐藏额度;兑换成功会使两种模式的额度缓存失效。
|
|
80
80
|
|
|
81
|
-
|
|
82
|
-
|
|
81
|
+
兑换重置次数前,本扩展会:
|
|
82
|
+
|
|
83
|
+
1. 确认当前 OpenAI 或 Codex 模型及展示额度对应的账户没有变化。
|
|
84
|
+
2. 确认运行时令牌与 Pi 通过 `/login` 保存的 OAuth 账户完全一致。OpenAI 模式会检查两套保存的凭据,并在兑换前重新核验应用匹配。
|
|
83
85
|
3. 显示即将消耗的重置次数并要求明确确认。`Cancel (Default)` 始终位于第一项;只有主动选择第二项才会继续。
|
|
84
86
|
4. 使用唯一请求 ID,并在重试时复用同一个 ID。
|
|
85
87
|
|
|
@@ -95,12 +97,12 @@ Codex 结果会按以下额度域分组:
|
|
|
95
97
|
## 安全边界
|
|
96
98
|
|
|
97
99
|
- 额度查询只通过 `ctx.modelRegistry.getProviderAuth()` 解析凭据。
|
|
98
|
-
-
|
|
100
|
+
- 账户重置还会通过公开的 `readStoredCredential()` API 读取 Pi 保存的 OAuth 凭据,仅用于确认其与当前运行时账户完全一致。
|
|
99
101
|
- Grok 不会读取 `~/.grok/auth.json`,也不会用 API Key 代替订阅 OAuth。
|
|
100
102
|
- 凭据不会写入缓存、会话、状态栏或错误消息;缓存键只保存进程内 HMAC 指纹。
|
|
101
103
|
- Codex 邮箱仅在本地解析后显示于 `/usage` 账户区域,不会进入底部状态或结构化状态事件。
|
|
102
104
|
- 凭据只会发送到对应的官方域名;自定义代理和自定义基础 URL 会被拒绝。
|
|
103
|
-
- Codex
|
|
105
|
+
- 账户重置兑换(OpenAI / Codex)是唯一的写操作。只有存在可兑换次数时才会显示,并且始终要求明确确认。
|
|
104
106
|
|
|
105
107
|
## 开发
|
|
106
108
|
|
|
@@ -129,7 +131,7 @@ pi --no-extensions --offline -e ./index.ts --list-models
|
|
|
129
131
|
|
|
130
132
|
## 稳定性
|
|
131
133
|
|
|
132
|
-
OpenAI 应用额度也依赖未公开的 ChatGPT
|
|
134
|
+
OpenAI 应用额度也依赖未公开的 ChatGPT 接口。OpenAI 会拒绝 Sign in with ChatGPT 令牌访问这些 ChatGPT 用量和重置接口(HTTP 401),因此必须配套 Codex 登录:用同一账户/工作区执行一次 `/login openai-codex`。它只用于读取用量,当前模型仍可保持 OpenAI。未登录时,可在 https://chatgpt.com/settings/usage 查看用量。账户/工作区不匹配、找不到应用注册或额度窗口时会报告错误,不展示其他账户的额度。`App Allowance` 表示允许应用使用的套餐份额,不是剩余额度百分比。`Source` 明确标注这是 Pi Codex 登录账户内匹配应用的数据;应用 ID 匹配不是对两套令牌身份的独立验签证明。
|
|
133
135
|
|
|
134
136
|
Codex 重置、Grok 账单和 Kimi 额度依赖未公开的提供商 API,这些 API 可能发生变化。如果 API 调用失败,本扩展只会报告查询错误,不会退回到不受控制的凭据或代理路径。
|
|
135
137
|
|
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 for OpenAI, Codex, OpenCode Go, Grok, and Kimi, plus Codex reset credits in Pi",
|
|
3
|
+
"version": "1.3.1",
|
|
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
|
@@ -43,13 +43,6 @@ export function codexResetCount(report: UsageReport): number | undefined {
|
|
|
43
43
|
: undefined;
|
|
44
44
|
}
|
|
45
45
|
|
|
46
|
-
export function genericCodexResetOption(): CodexResetOption {
|
|
47
|
-
return {
|
|
48
|
-
title: "Full Reset",
|
|
49
|
-
description: "Resets the current usage windows.",
|
|
50
|
-
};
|
|
51
|
-
}
|
|
52
|
-
|
|
53
46
|
export function resetOptionExpiration(option: CodexResetOption): string {
|
|
54
47
|
if (option.expiresAt === undefined) return "No Expiry";
|
|
55
48
|
const expiration = new Date(option.expiresAt * 1_000);
|
|
@@ -105,8 +98,13 @@ export function verifyCodexStoredOAuthCredential(
|
|
|
105
98
|
return accountId;
|
|
106
99
|
}
|
|
107
100
|
|
|
101
|
+
/**
|
|
102
|
+
* Offer only explicit, plan-supported, unexpired tickets. Redemption is
|
|
103
|
+
* irreversible, so a summary count alone never becomes a server-chosen reset.
|
|
104
|
+
*/
|
|
108
105
|
export function normalizeCodexResetCreditsPayload(
|
|
109
106
|
payload: Record<string, unknown>,
|
|
107
|
+
options: { now?: number } = {},
|
|
110
108
|
): CodexResetAvailability {
|
|
111
109
|
const availableCount = nonnegativeInteger(payload.available_count);
|
|
112
110
|
if (availableCount === undefined) {
|
|
@@ -117,7 +115,7 @@ export function normalizeCodexResetCreditsPayload(
|
|
|
117
115
|
if (payload.credits !== undefined && !Array.isArray(payload.credits)) {
|
|
118
116
|
throw new Error("Codex reset credits response returned invalid credits.");
|
|
119
117
|
}
|
|
120
|
-
const
|
|
118
|
+
const resetOptions: CodexResetOption[] = [];
|
|
121
119
|
for (const rawCredit of payload.credits ?? []) {
|
|
122
120
|
const credit = asObject(rawCredit);
|
|
123
121
|
if (
|
|
@@ -127,17 +125,19 @@ export function normalizeCodexResetCreditsPayload(
|
|
|
127
125
|
) {
|
|
128
126
|
continue;
|
|
129
127
|
}
|
|
130
|
-
|
|
128
|
+
if (credit.is_supported_by_plan !== true) continue;
|
|
129
|
+
const option = normalizeResetOption(credit);
|
|
130
|
+
if (option.expiresAt !== undefined &&
|
|
131
|
+
option.expiresAt * 1_000 <= (options.now ?? Date.now())) continue;
|
|
132
|
+
resetOptions.push(option);
|
|
131
133
|
}
|
|
132
|
-
|
|
134
|
+
resetOptions.sort(
|
|
133
135
|
(left, right) =>
|
|
134
136
|
(left.expiresAt ?? Number.MAX_SAFE_INTEGER) -
|
|
135
137
|
(right.expiresAt ?? Number.MAX_SAFE_INTEGER),
|
|
136
138
|
);
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
options.push(genericCodexResetOption());
|
|
140
|
-
return { availableCount, options };
|
|
139
|
+
resetOptions.splice(Math.min(availableCount, 32));
|
|
140
|
+
return { availableCount: resetOptions.length, options: resetOptions };
|
|
141
141
|
}
|
|
142
142
|
|
|
143
143
|
export function parseCodexResetOutcome(
|
|
@@ -199,7 +199,7 @@ function isOutcomeCode(value: unknown): value is CodexResetOutcomeCode {
|
|
|
199
199
|
);
|
|
200
200
|
}
|
|
201
201
|
|
|
202
|
-
function codexAccountIdFromAccessToken(access: string): string | undefined {
|
|
202
|
+
export function codexAccountIdFromAccessToken(access: string): string | undefined {
|
|
203
203
|
try {
|
|
204
204
|
const parts = access.split(".");
|
|
205
205
|
if (parts.length !== 3 || !parts[1]) return undefined;
|
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,22 +34,22 @@ 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
|
-
if (!adapter) throw new Error(
|
|
43
|
+
const adapter = adapterForProvider(model.provider);
|
|
44
|
+
if (!adapter) throw new Error(`Usage support for ${model.provider} is unavailable.`);
|
|
44
45
|
const auth = await resolveUsageAuth(ctx, adapter, salt);
|
|
45
46
|
if (`${ctx.model?.provider}/${ctx.model?.id}` !== expectedModel) {
|
|
46
47
|
throw new Error(
|
|
47
|
-
"The current model changed while resolving
|
|
48
|
+
"The current model changed while resolving reset authentication.",
|
|
48
49
|
);
|
|
49
50
|
}
|
|
50
51
|
if (!auth)
|
|
51
|
-
throw new Error(
|
|
52
|
+
throw new Error(`No runtime credential is configured for ${adapter.displayName}.`);
|
|
52
53
|
|
|
53
54
|
const resolvedAccess =
|
|
54
55
|
bearerToken(headerValue(auth.headers, "Authorization")) ?? auth.apiKey;
|
|
@@ -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
|
],
|
|
@@ -100,6 +110,9 @@ export async function consumeCodexResetCredit(
|
|
|
100
110
|
): Promise<CodexResetOutcome> {
|
|
101
111
|
if (!redeemRequestId)
|
|
102
112
|
throw new Error("Codex reset request ID must not be empty.");
|
|
113
|
+
if (!option.creditId) {
|
|
114
|
+
throw new Error("Account resets require an explicitly selected credit.");
|
|
115
|
+
}
|
|
103
116
|
return parseCodexResetOutcome(
|
|
104
117
|
await fetchProviderJson(
|
|
105
118
|
RESET_CONSUME_URL,
|
|
@@ -111,7 +124,7 @@ export async function consumeCodexResetCredit(
|
|
|
111
124
|
method: "POST",
|
|
112
125
|
body: {
|
|
113
126
|
redeem_request_id: redeemRequestId,
|
|
114
|
-
|
|
127
|
+
credit_id: option.creditId,
|
|
115
128
|
},
|
|
116
129
|
},
|
|
117
130
|
),
|
package/src/providers/openai.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { sanitizeDisplayText } from "../core.ts";
|
|
2
2
|
import type { UsageBucket, UsageReport } from "../types.ts";
|
|
3
|
+
import { normalizeCodexUsage } from "./codex.ts";
|
|
3
4
|
|
|
4
5
|
export const OPENAI_PROVIDER_ID = "openai";
|
|
5
6
|
|
|
@@ -87,6 +88,52 @@ export function normalizeOpenAIUsage(
|
|
|
87
88
|
};
|
|
88
89
|
}
|
|
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
|
+
|
|
90
137
|
function asObject(value: unknown): Record<string, unknown> | undefined {
|
|
91
138
|
return value && typeof value === "object" && !Array.isArray(value)
|
|
92
139
|
? value as Record<string, unknown>
|
package/src/query.ts
CHANGED
|
@@ -9,6 +9,10 @@ import {
|
|
|
9
9
|
redactUsageError,
|
|
10
10
|
} from "./core.ts";
|
|
11
11
|
import { CODEX_PROVIDER_ID } from "./providers/codex-constants.ts";
|
|
12
|
+
import {
|
|
13
|
+
codexAccountIdFromAccessToken,
|
|
14
|
+
normalizeCodexResetCreditsPayload,
|
|
15
|
+
} from "./codex-reset-core.ts";
|
|
12
16
|
import {
|
|
13
17
|
codexEmailFromAuthorization,
|
|
14
18
|
normalizeCodexUsage,
|
|
@@ -23,7 +27,7 @@ import {
|
|
|
23
27
|
import { normalizeKimiUsage } from "./providers/kimi.ts";
|
|
24
28
|
import {
|
|
25
29
|
OPENAI_PROVIDER_ID,
|
|
26
|
-
|
|
30
|
+
normalizeOpenAIPlanUsage,
|
|
27
31
|
openaiClientIdFromAuthorization,
|
|
28
32
|
} from "./providers/openai.ts";
|
|
29
33
|
import { normalizeOpenCodeGoUsage } from "./providers/opencode-go.ts";
|
|
@@ -34,6 +38,8 @@ import type {
|
|
|
34
38
|
} from "./types.ts";
|
|
35
39
|
|
|
36
40
|
const CODEX_USAGE_URL = "https://chatgpt.com/backend-api/wham/usage";
|
|
41
|
+
const RESET_CREDITS_URL =
|
|
42
|
+
"https://chatgpt.com/backend-api/wham/rate-limit-reset-credits";
|
|
37
43
|
const OPENCODE_GO_USAGE_URL = "https://opencode.ai/zen/go/v1/usage";
|
|
38
44
|
const KIMI_USAGE_URL = "https://api.kimi.com/coding/v1/usages";
|
|
39
45
|
const GROK_USER_URL = "https://cli-chat-proxy.grok.com/v1/user";
|
|
@@ -59,20 +65,21 @@ export const SUPPORTED_ADAPTERS: readonly UsageProviderAdapter[] = [
|
|
|
59
65
|
providerIds: [OPENAI_PROVIDER_ID],
|
|
60
66
|
officialOrigins: ["https://api.openai.com"],
|
|
61
67
|
requiresOAuth: true,
|
|
62
|
-
semantics: { kind: "consumer-subscription", label: "ChatGPT app
|
|
68
|
+
semantics: { kind: "consumer-subscription", label: "ChatGPT plan and app limits" },
|
|
63
69
|
async query(auth, signal, timeoutMs) {
|
|
64
70
|
if (!auth.openaiClientId) throw new Error("OpenAI application identity is unavailable.");
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
71
|
+
const [appPayload, planPayload] = await Promise.all([
|
|
72
|
+
fetchProviderJson(`${CODEX_USAGE_URL}/chatpass/apps`, auth, signal, timeoutMs, "OpenAI app usage endpoint"),
|
|
73
|
+
fetchProviderJson(CODEX_USAGE_URL, auth, signal, timeoutMs, "OpenAI plan usage endpoint"),
|
|
74
|
+
]);
|
|
75
|
+
const report = normalizeOpenAIPlanUsage(appPayload, planPayload, auth.openaiClientId, Date.now());
|
|
76
|
+
const resetCount = await fetchRedeemableResetCount(auth, signal, timeoutMs);
|
|
77
|
+
if (resetCount === undefined) {
|
|
78
|
+
report.notes = ["Account reset availability could not be verified."];
|
|
79
|
+
} else {
|
|
80
|
+
report.metrics.push({ id: "reset-credits", label: "Account Resets", value: resetCount, unit: "count" });
|
|
81
|
+
}
|
|
82
|
+
return report;
|
|
76
83
|
},
|
|
77
84
|
},
|
|
78
85
|
{
|
|
@@ -85,17 +92,30 @@ export const SUPPORTED_ADAPTERS: readonly UsageProviderAdapter[] = [
|
|
|
85
92
|
label: "ChatGPT subscription limits",
|
|
86
93
|
},
|
|
87
94
|
async query(auth, signal, timeoutMs) {
|
|
88
|
-
|
|
89
|
-
|
|
95
|
+
const [payload, resetCount] = await Promise.all([
|
|
96
|
+
fetchProviderJson(
|
|
90
97
|
CODEX_USAGE_URL,
|
|
91
98
|
auth,
|
|
92
99
|
signal,
|
|
93
100
|
timeoutMs,
|
|
94
101
|
"Codex usage endpoint",
|
|
95
102
|
),
|
|
103
|
+
fetchRedeemableResetCount(auth, signal, timeoutMs),
|
|
104
|
+
]);
|
|
105
|
+
// The usage summary also counts tickets the reset menu would refuse.
|
|
106
|
+
const report = normalizeCodexUsage(
|
|
107
|
+
{
|
|
108
|
+
...payload,
|
|
109
|
+
rate_limit_reset_credits:
|
|
110
|
+
resetCount === undefined ? undefined : { available_count: resetCount },
|
|
111
|
+
},
|
|
96
112
|
Date.now(),
|
|
97
113
|
codexEmailFromAuthorization(auth.headers.Authorization),
|
|
98
114
|
);
|
|
115
|
+
if (resetCount === undefined) {
|
|
116
|
+
report.notes = ["Reset availability could not be verified."];
|
|
117
|
+
}
|
|
118
|
+
return report;
|
|
99
119
|
},
|
|
100
120
|
},
|
|
101
121
|
{
|
|
@@ -260,7 +280,8 @@ export async function resolveUsageAuth(
|
|
|
260
280
|
const codexAdapter = adapterForProvider(CODEX_PROVIDER_ID)!;
|
|
261
281
|
const companion = await resolveUsageAuth(ctx, { ...codexAdapter, requiresOAuth: true }, salt);
|
|
262
282
|
if (!companion) {
|
|
263
|
-
|
|
283
|
+
// ChatGPT backend usage rejects these app tokens (401 rejected_by_access_enforcement).
|
|
284
|
+
throw new Error("OpenAI rejects Sign in with ChatGPT tokens for ChatGPT usage and reset data. Run /login openai-codex once with the same ChatGPT account/workspace; it is used only to read usage, so keep OpenAI as the active model. You can also check https://chatgpt.com/settings/usage.");
|
|
264
285
|
}
|
|
265
286
|
return {
|
|
266
287
|
actualProviderId: model.provider,
|
|
@@ -283,6 +304,37 @@ export async function resolveUsageAuth(
|
|
|
283
304
|
};
|
|
284
305
|
}
|
|
285
306
|
|
|
307
|
+
/**
|
|
308
|
+
* Undefined means unverified: usage still displays, but no reset is offered.
|
|
309
|
+
* Scope the listing to the backend token's own account, as redemption does.
|
|
310
|
+
*/
|
|
311
|
+
async function fetchRedeemableResetCount(
|
|
312
|
+
auth: ResolvedUsageAuth,
|
|
313
|
+
signal: AbortSignal,
|
|
314
|
+
timeoutMs: number,
|
|
315
|
+
): Promise<number | undefined> {
|
|
316
|
+
const access = /^Bearer\s+(\S+)$/iu.exec(
|
|
317
|
+
headerValue(auth.headers, "Authorization") ?? "",
|
|
318
|
+
)?.[1];
|
|
319
|
+
const accountId = access ? codexAccountIdFromAccessToken(access) : undefined;
|
|
320
|
+
if (!accountId) return undefined;
|
|
321
|
+
try {
|
|
322
|
+
return normalizeCodexResetCreditsPayload(
|
|
323
|
+
await fetchProviderJson(
|
|
324
|
+
RESET_CREDITS_URL,
|
|
325
|
+
auth,
|
|
326
|
+
signal,
|
|
327
|
+
timeoutMs,
|
|
328
|
+
"Reset credits endpoint",
|
|
329
|
+
{ headers: { "chatgpt-account-id": accountId } },
|
|
330
|
+
),
|
|
331
|
+
).availableCount;
|
|
332
|
+
} catch (error) {
|
|
333
|
+
if (isAbortError(error) || signal.aborted) throw error;
|
|
334
|
+
return undefined;
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
|
|
286
338
|
export async function queryProviderUsage(
|
|
287
339
|
adapter: UsageProviderAdapter,
|
|
288
340
|
auth: ResolvedUsageAuth,
|
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
|
@@ -51,6 +51,8 @@ export interface ResolvedUsageAuth {
|
|
|
51
51
|
actualProviderId: string;
|
|
52
52
|
/** Active OpenAI OAuth registration, matched against the ChatGPT app list. */
|
|
53
53
|
openaiClientId?: string;
|
|
54
|
+
/** Original usage identity, retained when reset auth adds account headers. */
|
|
55
|
+
usageFingerprint?: string;
|
|
54
56
|
apiKey?: string;
|
|
55
57
|
headers: Record<string, string>;
|
|
56
58
|
fingerprint: string;
|
package/src/usage.ts
CHANGED
|
@@ -20,7 +20,6 @@ import {
|
|
|
20
20
|
CODEX_RESET_CONFIRMATION_OPTIONS,
|
|
21
21
|
codexResetCount,
|
|
22
22
|
formatCodexResetOutcome,
|
|
23
|
-
genericCodexResetOption,
|
|
24
23
|
isCodexResetConfirmed,
|
|
25
24
|
resetOptionExpiration,
|
|
26
25
|
type CodexResetOption,
|
|
@@ -32,6 +31,7 @@ import {
|
|
|
32
31
|
} from "./codex-resets.ts";
|
|
33
32
|
import { formatProviderState } from "./format.ts";
|
|
34
33
|
import { CODEX_PROVIDER_ID } from "./providers/codex-constants.ts";
|
|
34
|
+
import { OPENAI_PROVIDER_ID } from "./providers/openai.ts";
|
|
35
35
|
import {
|
|
36
36
|
buildUsageStatusEvent,
|
|
37
37
|
formatUsageStatusline,
|
|
@@ -405,90 +405,98 @@ export default function subscriptionUsage(pi: ExtensionAPI): void {
|
|
|
405
405
|
controller: AbortController,
|
|
406
406
|
): Promise<StableCurrent | undefined> {
|
|
407
407
|
if (
|
|
408
|
-
ctx.model?.provider
|
|
408
|
+
![CODEX_PROVIDER_ID, OPENAI_PROVIDER_ID].includes(ctx.model?.provider ?? "") ||
|
|
409
409
|
current.outcome.state.status !== "ready"
|
|
410
410
|
) {
|
|
411
411
|
ctx.ui.notify(
|
|
412
|
-
"
|
|
412
|
+
"Account resets require the current OpenAI or Codex OAuth account.",
|
|
413
413
|
"warning",
|
|
414
414
|
);
|
|
415
415
|
return undefined;
|
|
416
416
|
}
|
|
417
|
-
const
|
|
417
|
+
const expectedModel = modelIdentity(current.model);
|
|
418
|
+
const isOpenAI = current.model?.provider === OPENAI_PROVIDER_ID;
|
|
419
|
+
const resetNoun = isOpenAI ? "account" : "Codex";
|
|
420
|
+
if (modelIdentity(ctx.model) !== expectedModel) throw new Error("Model changed; reset cancelled.");
|
|
418
421
|
let auth = await awaitWithDeadline(
|
|
419
422
|
() => resolveCodexResetAuth(ctx),
|
|
420
423
|
controller.signal,
|
|
421
424
|
QUERY_TIMEOUT_MS,
|
|
422
|
-
"resolving
|
|
425
|
+
"resolving reset authentication",
|
|
423
426
|
);
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
availability = await listCodexResetCredits(
|
|
427
|
-
auth,
|
|
428
|
-
controller.signal,
|
|
429
|
-
QUERY_TIMEOUT_MS,
|
|
430
|
-
);
|
|
431
|
-
} catch (error) {
|
|
432
|
-
if (summaryCount <= 0) throw error;
|
|
433
|
-
availability = {
|
|
434
|
-
availableCount: summaryCount,
|
|
435
|
-
options: [genericCodexResetOption()],
|
|
436
|
-
};
|
|
427
|
+
if (auth.usageFingerprint !== current.outcome.fingerprint) {
|
|
428
|
+
throw new Error("Account changed since usage was displayed; run /usage again.");
|
|
437
429
|
}
|
|
430
|
+
// A failed listing never falls back to an unscoped, server-chosen reset.
|
|
431
|
+
const availability = await listCodexResetCredits(
|
|
432
|
+
auth,
|
|
433
|
+
controller.signal,
|
|
434
|
+
QUERY_TIMEOUT_MS,
|
|
435
|
+
);
|
|
438
436
|
if (availability.availableCount <= 0 || availability.options.length === 0) {
|
|
439
|
-
ctx.ui.notify(
|
|
437
|
+
ctx.ui.notify(`No ${resetNoun} reset credits available.`, "info");
|
|
440
438
|
return undefined;
|
|
441
439
|
}
|
|
442
440
|
const labels = availability.options.map(
|
|
443
441
|
(option: CodexResetOption, index: number) =>
|
|
444
442
|
`${index + 1}. ${option.title} · ${resetOptionExpiration(option)}`,
|
|
445
443
|
);
|
|
446
|
-
const selected = await ctx.ui.select(
|
|
444
|
+
const selected = await ctx.ui.select(
|
|
445
|
+
isOpenAI ? "Choose an Account Reset" : "Choose a Codex Reset",
|
|
446
|
+
labels,
|
|
447
|
+
);
|
|
447
448
|
if (!selected) return undefined;
|
|
448
449
|
const option = availability.options[labels.indexOf(selected)];
|
|
449
450
|
if (!option) return undefined;
|
|
450
451
|
const confirmation = await ctx.ui.select(
|
|
451
|
-
`Redeem one
|
|
452
|
+
`Redeem one ${resetNoun} 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." : ""}`,
|
|
452
453
|
[...CODEX_RESET_CONFIRMATION_OPTIONS],
|
|
453
454
|
);
|
|
454
455
|
if (!isCodexResetConfirmed(confirmation)) return undefined;
|
|
455
456
|
|
|
456
|
-
const expectedModel = modelIdentity(ctx.model);
|
|
457
457
|
const expectedFingerprint = auth.fingerprint;
|
|
458
458
|
const requestId = randomUUID();
|
|
459
|
+
let submitted = false;
|
|
459
460
|
while (!controller.signal.aborted) {
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
461
|
+
try {
|
|
462
|
+
auth = await awaitWithDeadline(
|
|
463
|
+
() => resolveCodexResetAuth(ctx),
|
|
464
|
+
controller.signal,
|
|
465
|
+
QUERY_TIMEOUT_MS,
|
|
466
|
+
"revalidating reset authentication",
|
|
467
|
+
);
|
|
468
|
+
if (
|
|
469
|
+
modelIdentity(ctx.model) !== expectedModel ||
|
|
470
|
+
auth.fingerprint !== expectedFingerprint
|
|
471
|
+
) {
|
|
472
|
+
throw new Error("Model or account changed; reset not submitted.");
|
|
473
|
+
}
|
|
474
|
+
if (isOpenAI) {
|
|
475
|
+
await queryProviderUsage(adapterForProvider(OPENAI_PROVIDER_ID)!, auth, controller.signal, QUERY_TIMEOUT_MS);
|
|
476
|
+
const checked = await awaitWithDeadline(() => resolveCodexResetAuth(ctx), controller.signal, QUERY_TIMEOUT_MS, "revalidating account reset authentication");
|
|
477
|
+
if (checked.fingerprint !== expectedFingerprint || modelIdentity(ctx.model) !== expectedModel) {
|
|
478
|
+
throw new Error("OpenAI or Codex account changed; reset not submitted.");
|
|
479
|
+
}
|
|
480
|
+
auth = checked;
|
|
481
|
+
}
|
|
482
|
+
} catch (error) {
|
|
483
|
+
if (isAbortError(error) || !sessionActive) throw error;
|
|
484
|
+
if (!submitted) throw error;
|
|
485
|
+
// A previous POST may have succeeded even though its response was lost.
|
|
486
|
+
ctx.ui.notify("Reset result uncertain; retry stopped during account or usage verification. Run /usage to check your quota and reset credits.", "warning");
|
|
487
|
+
return undefined;
|
|
471
488
|
}
|
|
489
|
+
|
|
490
|
+
let outcome;
|
|
472
491
|
try {
|
|
473
|
-
|
|
492
|
+
submitted = true;
|
|
493
|
+
outcome = await consumeCodexResetCredit(
|
|
474
494
|
auth,
|
|
475
495
|
option,
|
|
476
496
|
requestId,
|
|
477
497
|
controller.signal,
|
|
478
498
|
QUERY_TIMEOUT_MS,
|
|
479
499
|
);
|
|
480
|
-
cache.clearProvider(CODEX_PROVIDER_ID);
|
|
481
|
-
failureBackoff.clear();
|
|
482
|
-
const refreshed = await queryStableCurrent(ctx, true, controller.signal);
|
|
483
|
-
if (refreshed?.model) {
|
|
484
|
-
publishStatus(ctx, refreshed.outcome, refreshed.model, sessionActive);
|
|
485
|
-
}
|
|
486
|
-
const remaining =
|
|
487
|
-
refreshed?.outcome.state.status === "ready"
|
|
488
|
-
? codexResetCount(refreshed.outcome.state.report)
|
|
489
|
-
: undefined;
|
|
490
|
-
ctx.ui.notify(formatCodexResetOutcome(outcome, remaining), "info");
|
|
491
|
-
return refreshed;
|
|
492
500
|
} catch (error) {
|
|
493
501
|
if (isAbortError(error) || !sessionActive) throw error;
|
|
494
502
|
const retryAction = "Retry with Same Request ID";
|
|
@@ -497,9 +505,30 @@ export default function subscriptionUsage(pi: ExtensionAPI): void {
|
|
|
497
505
|
"Cancel",
|
|
498
506
|
]);
|
|
499
507
|
if (retry !== retryAction) {
|
|
500
|
-
ctx.ui.notify(`Reset
|
|
508
|
+
ctx.ui.notify(`Reset result uncertain; run /usage to check your quota and reset credits. ${errorMessage(error)}`, "warning");
|
|
501
509
|
return undefined;
|
|
502
510
|
}
|
|
511
|
+
continue;
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
// A confirmed consume result must never become another consume retry.
|
|
515
|
+
cache.clearProvider(CODEX_PROVIDER_ID);
|
|
516
|
+
cache.clearProvider(OPENAI_PROVIDER_ID);
|
|
517
|
+
failureBackoff.clear();
|
|
518
|
+
ctx.ui.notify(formatCodexResetOutcome(outcome, undefined), "info");
|
|
519
|
+
try {
|
|
520
|
+
const refreshed = await queryStableCurrent(ctx, true, controller.signal);
|
|
521
|
+
if (!refreshed || refreshed.outcome.state.status !== "ready") {
|
|
522
|
+
ctx.ui.notify("Reset result confirmed, but usage refresh failed. Run /usage again.", "warning");
|
|
523
|
+
}
|
|
524
|
+
if (refreshed?.model) {
|
|
525
|
+
publishStatus(ctx, refreshed.outcome, refreshed.model, sessionActive);
|
|
526
|
+
}
|
|
527
|
+
return refreshed;
|
|
528
|
+
} catch (error) {
|
|
529
|
+
if (isAbortError(error) || !sessionActive) throw error;
|
|
530
|
+
ctx.ui.notify("Reset result confirmed, but usage refresh or display failed. Run /usage again.", "warning");
|
|
531
|
+
return undefined;
|
|
503
532
|
}
|
|
504
533
|
}
|
|
505
534
|
return undefined;
|
|
@@ -526,7 +555,7 @@ export default function subscriptionUsage(pi: ExtensionAPI): void {
|
|
|
526
555
|
publishStatus(ctx, current.outcome, current.model, sessionActive);
|
|
527
556
|
}
|
|
528
557
|
if (
|
|
529
|
-
ctx.model?.provider
|
|
558
|
+
![CODEX_PROVIDER_ID, OPENAI_PROVIDER_ID].includes(ctx.model?.provider ?? "") ||
|
|
530
559
|
current.outcome.state.status !== "ready"
|
|
531
560
|
) {
|
|
532
561
|
return;
|