@specode/pi-subscription-usage 1.2.0 → 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 +11 -9
- package/README.zh-CN.md +11 -9
- 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 +47 -0
- package/src/query.ts +19 -13
- package/src/status.ts +3 -1
- package/src/types.ts +2 -0
- package/src/usage.ts +68 -32
package/README.md
CHANGED
|
@@ -6,7 +6,7 @@ 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: 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
10
|
|
|
11
11
|
- **OpenAI Codex** — 5-hour and weekly quota, model-specific quota, and confirmed reset-credit redemption.
|
|
12
12
|
- **OpenCode Go** — 5-hour, weekly, and monthly windows.
|
|
@@ -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 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.
|
|
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. 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. `
|
|
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.
|
|
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,7 +6,7 @@
|
|
|
6
6
|
|
|
7
7
|
支持以下提供商:
|
|
8
8
|
|
|
9
|
-
- **OpenAI(ChatGPT
|
|
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
10
|
|
|
11
11
|
- **OpenAI Codex**:5 小时与每周额度、模型专属额度,以及需要确认的重置次数兑换。
|
|
12
12
|
- **OpenCode Go**: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 模式使用 ChatGPT 用量页相同的 `/wham/rate-limit-reset-credits` 和 `/consume` 接口。只提供明确存在、可用、套餐支持且未过期的 `codex_rate_limits` 票据;列表查询失败时不会退回自动兑换。票据重置的是服务端定义的账户窗口,**不保证清空当前应用窗口**,确认框会说明这一范围。查询重置次数失败不会隐藏套餐和应用额度;兑换成功会使两种模式的额度缓存失效。
|
|
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 接口。缺少配套 Codex 登录时,通过 `/login` 登录 **OpenAI Codex**,无需切换当前 OpenAI 模型。账户/工作区不匹配、找不到应用注册或额度窗口时会报告错误,不展示其他账户的额度。`
|
|
134
|
+
OpenAI 应用额度也依赖未公开的 ChatGPT 接口。缺少配套 Codex 登录时,通过 `/login` 登录 **OpenAI Codex**,无需切换当前 OpenAI 模型。账户/工作区不匹配、找不到应用注册或额度窗口时会报告错误,不展示其他账户的额度。`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.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,
|
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,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,
|
|
@@ -23,7 +24,7 @@ import {
|
|
|
23
24
|
import { normalizeKimiUsage } from "./providers/kimi.ts";
|
|
24
25
|
import {
|
|
25
26
|
OPENAI_PROVIDER_ID,
|
|
26
|
-
|
|
27
|
+
normalizeOpenAIPlanUsage,
|
|
27
28
|
openaiClientIdFromAuthorization,
|
|
28
29
|
} from "./providers/openai.ts";
|
|
29
30
|
import { normalizeOpenCodeGoUsage } from "./providers/opencode-go.ts";
|
|
@@ -59,20 +60,25 @@ export const SUPPORTED_ADAPTERS: readonly UsageProviderAdapter[] = [
|
|
|
59
60
|
providerIds: [OPENAI_PROVIDER_ID],
|
|
60
61
|
officialOrigins: ["https://api.openai.com"],
|
|
61
62
|
requiresOAuth: true,
|
|
62
|
-
semantics: { kind: "consumer-subscription", label: "ChatGPT app
|
|
63
|
+
semantics: { kind: "consumer-subscription", label: "ChatGPT plan and app limits" },
|
|
63
64
|
async query(auth, signal, timeoutMs) {
|
|
64
65
|
if (!auth.openaiClientId) throw new Error("OpenAI application identity is unavailable.");
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
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;
|
|
76
82
|
},
|
|
77
83
|
},
|
|
78
84
|
{
|
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
|
@@ -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,
|
|
@@ -405,15 +406,19 @@ export default function subscriptionUsage(pi: ExtensionAPI): void {
|
|
|
405
406
|
controller: AbortController,
|
|
406
407
|
): Promise<StableCurrent | undefined> {
|
|
407
408
|
if (
|
|
408
|
-
ctx.model?.provider
|
|
409
|
+
![CODEX_PROVIDER_ID, OPENAI_PROVIDER_ID].includes(ctx.model?.provider ?? "") ||
|
|
409
410
|
current.outcome.state.status !== "ready"
|
|
410
411
|
) {
|
|
411
412
|
ctx.ui.notify(
|
|
412
|
-
"
|
|
413
|
+
"Account resets require the current OpenAI or Codex OAuth account.",
|
|
413
414
|
"warning",
|
|
414
415
|
);
|
|
415
416
|
return undefined;
|
|
416
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.");
|
|
417
422
|
const summaryCount = codexResetCount(current.outcome.state.report) ?? 0;
|
|
418
423
|
let auth = await awaitWithDeadline(
|
|
419
424
|
() => resolveCodexResetAuth(ctx),
|
|
@@ -421,6 +426,9 @@ export default function subscriptionUsage(pi: ExtensionAPI): void {
|
|
|
421
426
|
QUERY_TIMEOUT_MS,
|
|
422
427
|
"resolving Codex reset authentication",
|
|
423
428
|
);
|
|
429
|
+
if (auth.usageFingerprint !== current.outcome.fingerprint) {
|
|
430
|
+
throw new Error("Account changed since usage was displayed; run /usage again.");
|
|
431
|
+
}
|
|
424
432
|
let availability;
|
|
425
433
|
try {
|
|
426
434
|
availability = await listCodexResetCredits(
|
|
@@ -429,7 +437,7 @@ export default function subscriptionUsage(pi: ExtensionAPI): void {
|
|
|
429
437
|
QUERY_TIMEOUT_MS,
|
|
430
438
|
);
|
|
431
439
|
} catch (error) {
|
|
432
|
-
if (summaryCount <= 0) throw error;
|
|
440
|
+
if (isOpenAI || isAbortError(error) || summaryCount <= 0) throw error;
|
|
433
441
|
availability = {
|
|
434
442
|
availableCount: summaryCount,
|
|
435
443
|
options: [genericCodexResetOption()],
|
|
@@ -443,52 +451,59 @@ export default function subscriptionUsage(pi: ExtensionAPI): void {
|
|
|
443
451
|
(option: CodexResetOption, index: number) =>
|
|
444
452
|
`${index + 1}. ${option.title} · ${resetOptionExpiration(option)}`,
|
|
445
453
|
);
|
|
446
|
-
const selected = await ctx.ui.select(
|
|
454
|
+
const selected = await ctx.ui.select(`Choose a ${resetLabel} Reset`, labels);
|
|
447
455
|
if (!selected) return undefined;
|
|
448
456
|
const option = availability.options[labels.indexOf(selected)];
|
|
449
457
|
if (!option) return undefined;
|
|
450
458
|
const confirmation = await ctx.ui.select(
|
|
451
|
-
`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." : ""}`,
|
|
452
460
|
[...CODEX_RESET_CONFIRMATION_OPTIONS],
|
|
453
461
|
);
|
|
454
462
|
if (!isCodexResetConfirmed(confirmation)) return undefined;
|
|
455
463
|
|
|
456
|
-
const expectedModel = modelIdentity(ctx.model);
|
|
457
464
|
const expectedFingerprint = auth.fingerprint;
|
|
458
465
|
const requestId = randomUUID();
|
|
466
|
+
let submitted = false;
|
|
459
467
|
while (!controller.signal.aborted) {
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
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;
|
|
471
495
|
}
|
|
496
|
+
|
|
497
|
+
let outcome;
|
|
472
498
|
try {
|
|
473
|
-
|
|
499
|
+
submitted = true;
|
|
500
|
+
outcome = await consumeCodexResetCredit(
|
|
474
501
|
auth,
|
|
475
502
|
option,
|
|
476
503
|
requestId,
|
|
477
504
|
controller.signal,
|
|
478
505
|
QUERY_TIMEOUT_MS,
|
|
479
506
|
);
|
|
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
507
|
} catch (error) {
|
|
493
508
|
if (isAbortError(error) || !sessionActive) throw error;
|
|
494
509
|
const retryAction = "Retry with Same Request ID";
|
|
@@ -497,9 +512,30 @@ export default function subscriptionUsage(pi: ExtensionAPI): void {
|
|
|
497
512
|
"Cancel",
|
|
498
513
|
]);
|
|
499
514
|
if (retry !== retryAction) {
|
|
500
|
-
ctx.ui.notify(`Reset
|
|
515
|
+
ctx.ui.notify(`Reset result uncertain; run /usage to check your quota and reset credits. ${errorMessage(error)}`, "warning");
|
|
501
516
|
return undefined;
|
|
502
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;
|
|
503
539
|
}
|
|
504
540
|
}
|
|
505
541
|
return undefined;
|
|
@@ -526,7 +562,7 @@ export default function subscriptionUsage(pi: ExtensionAPI): void {
|
|
|
526
562
|
publishStatus(ctx, current.outcome, current.model, sessionActive);
|
|
527
563
|
}
|
|
528
564
|
if (
|
|
529
|
-
ctx.model?.provider
|
|
565
|
+
![CODEX_PROVIDER_ID, OPENAI_PROVIDER_ID].includes(ctx.model?.provider ?? "") ||
|
|
530
566
|
current.outcome.state.status !== "ready"
|
|
531
567
|
) {
|
|
532
568
|
return;
|