@specode/pi-subscription-usage 1.3.0 → 1.4.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 CHANGED
@@ -1,65 +1,99 @@
1
- # Pi Subscription Usage
1
+ # pi-subscription-usage
2
2
 
3
- [English](README.md) | [简体中文](README.zh-CN.md)
3
+ [English](./README.md) | [简体中文](./README.zh-CN.md)
4
4
 
5
- A Pi extension that shows the active account's subscription quota in one consistent view.
5
+ A [Pi](https://github.com/earendil-works/pi-mono) extension that shows your active provider's subscription quota in the footer status bar and a full breakdown via `/usage`.
6
6
 
7
- Supported providers:
7
+ Footer status bar:
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.
9
+ ```text
10
+ 5h 99% ↻2h13m · 1w 85% ↻3d4h
11
+ ```
12
+
13
+ `/usage` output:
14
+
15
+ ```text
16
+ OpenAI Codex
17
+ Shared Across Models:
18
+ 5h Window ████████████ 99% left · resets 08/27 12:13
19
+ 1w Window ██████████░░ 85% left · resets 08/30 14:00
20
+
21
+ gpt-5.6-spark:
22
+ 5h Window █░░░░░░░░░░░ 10% left · resets 08/27 11:40
23
+
24
+ Account:
25
+ Email user@example.com
26
+ Plan Pro
27
+ Resets Left 2
28
+ Extra Credit none
29
+ ```
30
+
31
+ ## Supported Providers
32
+
33
+ To sign in, run `/login`, pick `Sign in with an account` (Account below) or `Sign in with an API key` (API key below), then pick the name shown in the table.
34
+
35
+ | Provider | `/login` option | Quota shown | Reset credits | Extra extension |
36
+ | --- | --- | --- | --- | --- |
37
+ | OpenAI (ChatGPT) | Account → `OpenAI`, and Account → `OpenAI Codex (legacy)` | ChatGPT plan limits, current app limits | Yes (`Account Resets`) | |
38
+ | OpenAI Codex | Account → `OpenAI Codex (legacy)` | `5h`, `1w`, model-specific windows, account email | Yes (`Resets Left`) | |
39
+ | OpenCode Go | API key → `OpenCode Go` | `5h`, `1w`, `1m` | — | |
40
+ | xAI Grok | Account → `xAI` | `1w` and/or `1m` | — | |
41
+ | Kimi Coding | Account → `Kimi For Coding` | `5h`, `1w`, membership level | — | |
42
+ | Antigravity | Account → `Antigravity` | Gemini (`5h`, `1w`), Claude and GPT (`5h`, `1w`), Gemini 4 Argon (`1w`), plan, email, project | — | [`pi-antigravity`](https://github.com/Rahularya01/pi-antigravity) |
43
+
44
+ ### Provider Notes
45
+
46
+ #### OpenAI (ChatGPT)
10
47
 
11
- - **OpenAI Codex** — 5-hour and weekly quota, model-specific quota, and confirmed reset-credit redemption.
12
- - **OpenCode Go** — 5-hour, weekly, and monthly windows.
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
- - **Kimi Coding** — 5-hour and weekly windows, plus the membership plan reported by the usage API.
48
+ Sign in to both `OpenAI` and `OpenAI Codex (legacy)` with the same ChatGPT account and workspace, then keep chatting with an `OpenAI` model. OpenAI rejects the `OpenAI` sign-in on its usage endpoints, so the extension uses the `OpenAI Codex (legacy)` sign-in only to read usage. `/usage` lists website `Plan limits` separately from the current app's limits (`App Allowance` shows the configured cap share, not remaining quota), and the footer tracks `Plan limits`.
15
49
 
16
- The extension does not implement or modify Codex Fast mode and never rewrites model requests.
50
+ #### xAI Grok
51
+
52
+ Sign in with your SuperGrok account (Account → `xAI`). Signing in with an xAI API key does not show subscription quota. If you use the third-party `pi-xai-oauth` extension instead, its sign-in works too.
53
+
54
+ #### Antigravity
55
+
56
+ Install [`pi-antigravity`](https://github.com/Rahularya01/pi-antigravity) first (`pi install npm:pi-antigravity`). `Antigravity` then appears under `Sign in with an account` in `/login`. Quota is split into three separate shared pools: Gemini models (`5h` and `1w`), Claude and GPT models (`5h` and `1w`), and Gemini 4 Argon (`1w`). The footer shows the pool of the model you are using: Claude and GPT-OSS models show the Claude and GPT pool, Gemini 4 Argon shows the Argon pool, and other Gemini models show the Gemini pool. Quota data requires a paid Google AI subscription; free-tier accounts show `Unsupported` in `/usage` and display nothing in the footer instead of an error.
17
57
 
18
58
  ## Installation
19
59
 
20
- Install directly from GitHub:
60
+ From npm:
21
61
 
22
62
  ```bash
23
- pi install git:github.com/specode/pi-subscription-usage
63
+ pi install npm:@specode/pi-subscription-usage
24
64
  ```
25
65
 
26
- After the npm package is published, it can also be installed with:
66
+ From GitHub:
27
67
 
28
68
  ```bash
29
- pi install npm:@specode/pi-subscription-usage
69
+ pi install git:github.com/specode/pi-subscription-usage
30
70
  ```
31
71
 
32
- For local development:
72
+ From a local directory for development:
33
73
 
34
74
  ```bash
35
- pi install /absolute/path/to/pi-subscription-usage
75
+ pi install /path/to/pi-subscription-usage
36
76
  ```
37
77
 
38
- Pi packages execute with your full system permissions. Review third-party package source before installing it.
39
-
40
78
  ## Usage
41
79
 
42
- Run:
43
-
44
- ```text
45
- /usage
46
- ```
47
-
48
- Each invocation bypasses the cache and queries the current provider again. Quota windows use a uniform display with `MM/DD HH:mm` reset times. When a provider reports account metrics, they appear in a separate `Account` section after the quota windows.
80
+ Sign in through `/login` as described above, then select a model from that provider. From then on:
49
81
 
50
- Codex results are grouped by quota domain in this order:
82
+ - The footer status bar shows the active quota windows and refreshes after each turn and every 5 minutes (using a 5-minute cache).
83
+ - Running `/usage` always fetches fresh data for the active provider and shows progress bars, reset times (`MM/DD HH:mm`), and account details.
51
84
 
52
- 1. `Shared Across Models`
53
- 2. Model-specific sections
54
- 3. `Account`
85
+ ### Reset Credits (OpenAI and Codex)
55
86
 
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.
87
+ When your OpenAI or Codex account has redeemable rate-limit reset tickets, `/usage` offers to use one:
57
88
 
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.
89
+ - `Cancel (Default)` is selected by default, and an explicit confirmation is required before a ticket is consumed.
90
+ - Before redeeming, the extension checks that the active model and account have not changed and that the runtime token matches Pi's stored OAuth login.
91
+ - In OpenAI mode, a ticket resets server-defined account windows rather than specifically clearing the current app's limits.
92
+ - Redeeming a reset ticket is the only write operation in this extension.
59
93
 
60
94
  ## Configuration
61
95
 
62
- Create `~/.pi/agent/subscription-usage.json` for a global setting, or `.pi/subscription-usage.json` in a trusted project to override it:
96
+ Percentages show remaining quota by default. To show used quota instead, create `~/.pi/agent/subscription-usage.json` (global) or `.pi/subscription-usage.json` (trusted project override):
63
97
 
64
98
  ```json
65
99
  {
@@ -67,74 +101,38 @@ Create `~/.pi/agent/subscription-usage.json` for a global setting, or `.pi/subsc
67
101
  }
68
102
  ```
69
103
 
70
- `displayMode` accepts:
71
-
72
- - `"remaining"` — show quota remaining (default, preserving the existing behavior).
73
- - `"used"` — show quota consumed.
74
-
75
- The setting applies to the footer status, `/usage` quota bars, and the structured status event. Run `/reload` after editing the file.
76
-
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.
80
-
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.
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.
86
- 4. Uses a unique request ID and reuses it across retries.
87
-
88
- ## Status integration
89
-
90
- The extension publishes two status layers:
91
-
92
- - A plain `setStatus` string without provider names or icons, such as `5h 99% ↻2h13m · 1w 85% ↻3d4h · 1m 60%`. `↻` marks the countdown to each window's reset, shown only when the provider reports a future reset time. The footer refreshes every 5 minutes and after each agent turn, so the countdown can lag by up to about 5 minutes.
93
- - Structured window data through the `subscription-usage/status/v1` event.
104
+ | Value | Description |
105
+ | --- | --- |
106
+ | `"remaining"` | Show remaining quota percentage (default) |
107
+ | `"used"` | Show used quota percentage |
94
108
 
95
- Windows are always ordered as `5h / 1w / 1m / other`. Other extensions can consume the structured event to provide their own icons, colors, and layout without parsing display text. Ready events include `displayMode`; each window includes `displayPercent`, `remainingPercent`, and `usedPercent`. Consumers should render `displayPercent` while using the explicit remaining/used fields for semantic decisions such as colors or alerts. When the provider reports a future reset time, a window also carries `resetCountdown` (for example `2h13m`), computed at publish time with the same format and refresh cadence as the footer text; consumers can show it as-is instead of formatting `resetsAt` themselves.
109
+ Run `/reload` after changing the config file. `displayMode` applies to the footer status bar, `/usage` progress bars, and status events.
96
110
 
97
- ## Security boundaries
111
+ ## Privacy and Safety
98
112
 
99
- - Usage queries resolve credentials only through `ctx.modelRegistry.getProviderAuth()`.
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.
101
- - Grok never reads `~/.grok/auth.json` and never accepts an API key in place of subscription OAuth.
102
- - Credentials are never written to caches, sessions, the status line, or error messages. Cache keys contain only in-process HMAC fingerprints.
103
- - The Codex email is decoded locally for the `/usage` account panel and is not included in the footer or structured status event.
104
- - Credentials are sent only to the corresponding official domains. Custom proxies and custom base URLs are rejected.
105
- - Account reset redemption (OpenAI / Codex) is the only write operation. It is shown only when redeemable credits exist and always requires explicit confirmation.
113
+ - Credentials come only from Pi's own login (provider registry). The extension never reads browser cookies or other tools' credential files (for example, Grok never reads `~/.grok/auth.json`).
114
+ - Requests go only to each provider's official endpoints. Custom proxies and custom base URLs are refused.
115
+ - Tokens are never written to caches, session files, the status bar, or error messages.
116
+ - The extension does not modify model requests.
117
+ - Several provider usage endpoints are undocumented. If an endpoint changes, the extension shows an error rather than guessing.
106
118
 
107
119
  ## Development
108
120
 
109
- Requirements:
110
-
111
- - A current Pi installation.
112
- - A Node.js version that can run TypeScript files directly for the test suite.
113
-
114
- Run the tests:
115
-
116
121
  ```bash
122
+ # Run tests (requires Node.js with native TypeScript support)
117
123
  npm test
118
- ```
119
-
120
- Inspect the npm package contents:
121
124
 
122
- ```bash
125
+ # Check package contents
123
126
  npm run pack:check
124
- ```
125
-
126
- Load the extension directly without installing it:
127
127
 
128
- ```bash
128
+ # Load the extension directly in Pi without installing
129
129
  pi --no-extensions --offline -e ./index.ts --list-models
130
130
  ```
131
131
 
132
- ## Stability
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.
132
+ ### Status Events for Theme and Extension Authors
135
133
 
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.
134
+ The extension emits structured events on `subscription-usage/status/v1` so custom themes or status extensions can render quota data without parsing the footer string. Windows are ordered `5h` -> `1w` -> `1m` -> other. Ready payloads include `displayMode` and, for each window, `displayPercent`, `remainingPercent`, `usedPercent`, and `resetCountdown`.
137
135
 
138
136
  ## License
139
137
 
140
- [MIT](LICENSE). See [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md) for adapted third-party sources and licenses.
138
+ [MIT](./LICENSE). See [THIRD_PARTY_NOTICES.md](./THIRD_PARTY_NOTICES.md) for adapted sources and licenses.
package/README.zh-CN.md CHANGED
@@ -1,65 +1,99 @@
1
- # Pi Subscription Usage
1
+ # pi-subscription-usage
2
2
 
3
- [English](README.md) | [简体中文](README.zh-CN.md)
3
+ [English](./README.md) | [简体中文](./README.zh-CN.md)
4
4
 
5
- 一个用统一格式展示当前 Pi 账户订阅额度的扩展。
5
+ 一个 [Pi](https://github.com/earendil-works/pi-mono) 扩展:在底部状态栏显示当前订阅还剩多少额度,输入 `/usage` 查看完整明细。
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 账户的重置接口兑换,并非应用专属重置接口。
9
+ ```text
10
+ 5h 99% ↻2h13m · 1w 85% ↻3d4h
11
+ ```
10
12
 
11
- - **OpenAI Codex**:5 小时与每周额度、模型专属额度,以及需要确认的重置次数兑换。
12
- - **OpenCode Go**:5 小时、每周和每月窗口。
13
- - **Grok**:每周和/或每月额度;只使用 Pi 的 `xai` / `xai-auth` OAuth 凭据,并先验证账户身份。若 weekly `currentPeriod` 存在但省略了 `creditUsagePercent`,按已用 0% 处理(proto3 在周期重置后会省略 0)。统一账单账户仍会探测默认月度接口,但 weekly 窗口已经可展示时,月度探测失败不再让整次查询失败。窗口与其他提供商一样使用 `5h / 1w / 1m` 状态格式。
14
- - **Kimi Coding**:5 小时和每周窗口,以及额度接口返回的会员套餐。
13
+ `/usage` 输出示例:
15
14
 
16
- 本扩展不实现或修改 Codex Fast 模式,也不会改写模型请求。
15
+ ```text
16
+ OpenAI Codex
17
+ Shared Across Models:
18
+ 5h Window ████████████ 99% left · resets 08/27 12:13
19
+ 1w Window ██████████░░ 85% left · resets 08/30 14:00
20
+
21
+ gpt-5.6-spark:
22
+ 5h Window █░░░░░░░░░░░ 10% left · resets 08/27 11:40
23
+
24
+ Account:
25
+ Email user@example.com
26
+ Plan Pro
27
+ Resets Left 2
28
+ Extra Credit none
29
+ ```
17
30
 
18
- ## 安装
31
+ ## 支持的提供商
19
32
 
20
- 直接从 GitHub 安装:
33
+ 登录方法:输入 `/login`,先选 `Sign in with an account`(下表记为 Account)或 `Sign in with an API key`(下表记为 API key),再在列表里选下表中的名称。Pi 界面只有英文,这里的选项名称都按界面原文写。
21
34
 
22
- ```bash
23
- pi install git:github.com/specode/pi-subscription-usage
24
- ```
35
+ | 提供商 | `/login` 中选择 | 显示内容 | 重置券 | 额外扩展 |
36
+ | --- | --- | --- | --- | --- |
37
+ | OpenAI (ChatGPT) | Account → `OpenAI`,以及 Account → `OpenAI Codex (legacy)` | ChatGPT 套餐限额、当前应用限额 | 支持(`Account Resets`) | |
38
+ | OpenAI Codex | Account → `OpenAI Codex (legacy)` | `5h`、`1w`、模型专属窗口、账号邮箱 | 支持(`Resets Left`) | |
39
+ | OpenCode Go | API key → `OpenCode Go` | `5h`、`1w`、`1m` | — | |
40
+ | xAI Grok | Account → `xAI` | `1w` 和/或 `1m` | — | |
41
+ | Kimi Coding | Account → `Kimi For Coding` | `5h`、`1w`、会员等级 | — | |
42
+ | Antigravity | Account → `Antigravity` | Gemini(`5h`、`1w`)、Claude 与 GPT(`5h`、`1w`)、Gemini 4 Argon(`1w`)、套餐、邮箱、项目 | — | [`pi-antigravity`](https://github.com/Rahularya01/pi-antigravity) |
43
+
44
+ ### 提供商说明
45
+
46
+ #### OpenAI (ChatGPT)
47
+
48
+ 用同一个 ChatGPT 账号和工作区,分别登录 `OpenAI` 和 `OpenAI Codex (legacy)`,平时对话继续用 `OpenAI` 下的模型就行。OpenAI 的用量接口不认 `OpenAI` 这个登录,所以扩展只借 `OpenAI Codex (legacy)` 的登录来读额度。`/usage` 会将网页端的套餐总限额(`Plan limits`)与当前应用限额分开显示(`App Allowance` 表示该应用的配额上限比例,而非剩余额度),底部状态栏显示 `Plan limits`。
25
49
 
26
- npm 包发布后,也可以这样安装:
50
+ #### xAI Grok
51
+
52
+ 用 SuperGrok 账号登录(Account → `xAI`)。用 xAI 的 API Key 登录看不到订阅额度。如果你装的是第三方扩展 `pi-xai-oauth`,用它登录也可以。
53
+
54
+ #### Antigravity
55
+
56
+ 需先安装 [`pi-antigravity`](https://github.com/Rahularya01/pi-antigravity)(`pi install npm:pi-antigravity`),之后 `/login` 的 `Sign in with an account` 列表里才会出现 `Antigravity`。额度分为三个独立的共享池:Gemini 模型(`5h` 与 `1w`)、Claude 与 GPT 模型(`5h` 与 `1w`)、Gemini 4 Argon(`1w`)。底部状态栏显示当前所用模型对应的额度池:用 Claude 或 GPT-OSS 模型时显示 Claude 与 GPT 池,用 Gemini 4 Argon 时显示 Argon 池,其他 Gemini 模型显示 Gemini 池。额度数据只对 Google AI 付费订阅开放;免费账号在 `/usage` 里显示 `Unsupported`,底部状态栏不显示内容,不会报错。
57
+
58
+ ## 安装
59
+
60
+ 从 npm 安装:
27
61
 
28
62
  ```bash
29
63
  pi install npm:@specode/pi-subscription-usage
30
64
  ```
31
65
 
32
- 本地开发时可以安装本地目录:
66
+ 从 GitHub 安装:
33
67
 
34
68
  ```bash
35
- pi install /absolute/path/to/pi-subscription-usage
69
+ pi install git:github.com/specode/pi-subscription-usage
36
70
  ```
37
71
 
38
- Pi package 拥有当前用户的完整系统权限。安装第三方 package 前,请先审查其源码。
39
-
40
- ## 使用
72
+ 从本地目录安装(开发调试):
41
73
 
42
- 运行:
43
-
44
- ```text
45
- /usage
74
+ ```bash
75
+ pi install /path/to/pi-subscription-usage
46
76
  ```
47
77
 
48
- 每次调用都会跳过缓存并重新查询当前提供商。所有额度窗口都使用统一格式,并以 `MM/DD HH:mm` 显示重置时间。提供商返回账户指标时,这些指标会统一显示在额度窗口之后的独立 `Account` 区域。
78
+ ## 使用说明
79
+
80
+ 按上面的方法登录,再选一个该提供商的模型,之后:
49
81
 
50
- Codex 结果会按以下额度域分组:
82
+ - 底部状态栏会自动显示当前额度窗口,在每轮对话结束后及每 5 分钟刷新一次(带 5 分钟缓存)。
83
+ - 执行 `/usage` 会跳过缓存直接拉取最新数据,显示进度条、重置时间(`MM/DD HH:mm`)及账号信息。
51
84
 
52
- 1. `Shared Across Models`
53
- 2. 各模型专属分组
54
- 3. `Account`
85
+ ### 使用重置券(OpenAI 与 Codex)
55
86
 
56
- 不同额度域的窗口不会交错。存在邮箱字段时,Codex `Account` 区域会显示从当前 OAuth Token 本地解析出的邮箱。需要刷新时再次运行 `/usage` 即可;命令不会显示刷新、切换提供商或查询所有提供商的菜单。
87
+ OpenAI 或 Codex 账号里有可用的限额重置券时,`/usage` 会提供使用入口:
57
88
 
58
- OpenAI 和 Codex 模式都仅在确认有可兑换重置次数时显示重置菜单。Grok 当前 API 只公开额度窗口和自然重置时间,没有经过验证的手动重置端点或重置次数,因此本扩展不会虚构重置操作。Grok 窗口仍通过与 Codex、OpenCode Go、Kimi 相同的 `/usage` 进度条和状态事件展示。
89
+ - 确认弹窗默认选中 `Cancel (Default)`,必须手动确认才会消耗重置券。
90
+ - 提交兑换前,扩展会检查当前模型和账号是否发生变动,并核对运行时令牌是否与 Pi 保存的 OAuth 登录信息一致。
91
+ - 在 OpenAI 模式下,重置券作用于服务端定义的账户级窗口,不一定单独清空当前应用的限额。
92
+ - 兑换重置券是本扩展唯一的写操作。
59
93
 
60
94
  ## 配置
61
95
 
62
- 可创建 `~/.pi/agent/subscription-usage.json` 作为全局配置,或在受信任项目中创建 `.pi/subscription-usage.json` 覆盖全局配置:
96
+ 百分比默认显示剩余额度。如需改为显示已用额度,可在 `~/.pi/agent/subscription-usage.json`(全局)或 `.pi/subscription-usage.json`(受信任项目的局部覆盖)中配置:
63
97
 
64
98
  ```json
65
99
  {
@@ -67,74 +101,38 @@ OpenAI 和 Codex 模式都仅在确认有可兑换重置次数时显示重置菜
67
101
  }
68
102
  ```
69
103
 
70
- `displayMode` 支持:
71
-
72
- - `"remaining"`:显示剩余额度(默认值,保持当前行为)。
73
- - `"used"`:显示已使用额度。
74
-
75
- 该配置同时作用于底部状态、`/usage` 额度条和结构化状态事件。修改配置文件后运行 `/reload`。
76
-
77
- ## OpenAI / Codex 重置安全措施
78
-
79
- OpenAI 模式使用 ChatGPT 用量页相同的 `/wham/rate-limit-reset-credits` 和 `/consume` 接口。只提供明确存在、可用、套餐支持且未过期的 `codex_rate_limits` 票据;列表查询失败时不会退回自动兑换。票据重置的是服务端定义的账户窗口,**不保证清空当前应用窗口**,确认框会说明这一范围。查询重置次数失败不会隐藏套餐和应用额度;兑换成功会使两种模式的额度缓存失效。
80
-
81
- 兑换重置次数前,本扩展会:
82
-
83
- 1. 确认当前 OpenAI 或 Codex 模型及展示额度对应的账户没有变化。
84
- 2. 确认运行时令牌与 Pi 通过 `/login` 保存的 OAuth 账户完全一致。OpenAI 模式会检查两套保存的凭据,并在兑换前重新核验应用匹配。
85
- 3. 显示即将消耗的重置次数并要求明确确认。`Cancel (Default)` 始终位于第一项;只有主动选择第二项才会继续。
86
- 4. 使用唯一请求 ID,并在重试时复用同一个 ID。
87
-
88
- ## 状态集成
89
-
90
- 本扩展提供两层状态输出:
91
-
92
- - 不含提供商名称或图标的普通 `setStatus` 文本,例如 `5h 99% ↻2h13m · 1w 85% ↻3d4h · 1m 60%`。`↻` 后是距离该窗口重置的倒计时,仅在提供商返回未来的重置时间时显示。底部状态每 5 分钟及每轮 agent 结束后刷新,因此倒计时最多可能滞后约 5 分钟。
93
- - 通过 `subscription-usage/status/v1` 事件发布的结构化窗口数据。
104
+ | 配置值 | 说明 |
105
+ | --- | --- |
106
+ | `"remaining"` | 显示剩余额度百分比(默认) |
107
+ | `"used"` | 显示已用额度百分比 |
94
108
 
95
- 窗口始终按 `5h / 1w / 1m / other` 排序。其他扩展可以直接消费结构化事件,自定义图标、颜色和布局,而不必解析显示文本。就绪事件包含 `displayMode`,每个窗口包含 `displayPercent`、`remainingPercent` 和 `usedPercent`;消费者应展示 `displayPercent`,并在颜色或告警等语义判断中使用明确的剩余/已用字段。提供商返回未来的重置时间时,窗口还包含 `resetCountdown`(例如 `2h13m`),在发布事件时计算,格式和刷新频率与底部状态文本一致;消费者可直接展示,无需自行根据 `resetsAt` 格式化。
109
+ 修改配置文件后执行 `/reload` 生效。`displayMode` 同时作用于底部状态栏、`/usage` 进度条和状态事件。
96
110
 
97
- ## 安全边界
111
+ ## 隐私与安全
98
112
 
99
- - 额度查询只通过 `ctx.modelRegistry.getProviderAuth()` 解析凭据。
100
- - 账户重置还会通过公开的 `readStoredCredential()` API 读取 Pi 保存的 OAuth 凭据,仅用于确认其与当前运行时账户完全一致。
101
- - Grok 不会读取 `~/.grok/auth.json`,也不会用 API Key 代替订阅 OAuth。
102
- - 凭据不会写入缓存、会话、状态栏或错误消息;缓存键只保存进程内 HMAC 指纹。
103
- - Codex 邮箱仅在本地解析后显示于 `/usage` 账户区域,不会进入底部状态或结构化状态事件。
104
- - 凭据只会发送到对应的官方域名;自定义代理和自定义基础 URL 会被拒绝。
105
- - 账户重置兑换(OpenAI / Codex)是唯一的写操作。只有存在可兑换次数时才会显示,并且始终要求明确确认。
113
+ - 仅从 Pi 自身的登录注册表读取凭据,不读取浏览器 Cookie 或其他工具的凭据文件(例如 Grok 不会读取 `~/.grok/auth.json`)。
114
+ - 仅向各提供商的官方接口发起请求,拒绝自定义代理和自定义 Base URL。
115
+ - 令牌不会写入缓存、会话文件、状态栏或报错信息。
116
+ - 不修改任何模型请求。
117
+ - 部分提供商的用量接口属于未公开接口;若接口变更,扩展会直接报错提示,不会猜测或伪造数据。
106
118
 
107
- ## 开发
108
-
109
- 要求:
110
-
111
- - 当前版本的 Pi。
112
- - 能够直接运行 TypeScript 文件的 Node.js 版本,用于执行测试。
113
-
114
- 运行测试:
119
+ ## 本地开发
115
120
 
116
121
  ```bash
122
+ # 运行测试(需要原生支持 TypeScript 的 Node.js 版本)
117
123
  npm test
118
- ```
119
-
120
- 检查 npm 包内容:
121
124
 
122
- ```bash
125
+ # 检查打包文件列表
123
126
  npm run pack:check
124
- ```
125
-
126
- 不安装、直接加载扩展:
127
127
 
128
- ```bash
128
+ # 不安装直接加载扩展验证
129
129
  pi --no-extensions --offline -e ./index.ts --list-models
130
130
  ```
131
131
 
132
- ## 稳定性
133
-
134
- OpenAI 应用额度也依赖未公开的 ChatGPT 接口。缺少配套 Codex 登录时,通过 `/login` 登录 **OpenAI Codex**,无需切换当前 OpenAI 模型。账户/工作区不匹配、找不到应用注册或额度窗口时会报告错误,不展示其他账户的额度。`App Allowance` 表示允许应用使用的套餐份额,不是剩余额度百分比。`Source` 明确标注这是 Pi Codex 登录账户内匹配应用的数据;应用 ID 匹配不是对两套令牌身份的独立验签证明。
132
+ ### 主题与状态栏扩展接入
135
133
 
136
- Codex 重置、Grok 账单和 Kimi 额度依赖未公开的提供商 API,这些 API 可能发生变化。如果 API 调用失败,本扩展只会报告查询错误,不会退回到不受控制的凭据或代理路径。
134
+ 扩展会在 `subscription-usage/status/v1` 事件通道发布结构化状态事件,供自定义主题或状态栏扩展直接渲染额度数据,无需解析状态栏文本。窗口固定按 `5h` -> `1w` -> `1m` -> 其他顺序排列;就绪事件包含 `displayMode`,每个窗口提供 `displayPercent`、`remainingPercent`、`usedPercent` 和 `resetCountdown`。
137
135
 
138
136
  ## 许可证
139
137
 
140
- 采用 [MIT](LICENSE) 许可证。改编的第三方源码及其许可证见 [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md)。
138
+ [MIT](./LICENSE)。改编的第三方源码及许可证信息见 [THIRD_PARTY_NOTICES.md](./THIRD_PARTY_NOTICES.md)。
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@specode/pi-subscription-usage",
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",
3
+ "version": "1.4.0",
4
+ "description": "Show subscription quota for OpenAI, Codex, OpenCode Go, Grok, Kimi, and Antigravity, plus OpenAI and Codex account reset credits in Pi",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "author": "Specode",
@@ -22,7 +22,8 @@
22
22
  "codex",
23
23
  "opencode",
24
24
  "grok",
25
- "kimi"
25
+ "kimi",
26
+ "antigravity"
26
27
  ],
27
28
  "files": [
28
29
  "index.ts",
@@ -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,9 +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>,
110
- options: { requireExplicitCredit?: boolean; now?: number } = {},
107
+ options: { now?: number } = {},
111
108
  ): CodexResetAvailability {
112
109
  const availableCount = nonnegativeInteger(payload.available_count);
113
110
  if (availableCount === undefined) {
@@ -128,9 +125,9 @@ export function normalizeCodexResetCreditsPayload(
128
125
  ) {
129
126
  continue;
130
127
  }
131
- if (options.requireExplicitCredit && credit.is_supported_by_plan !== true) continue;
128
+ if (credit.is_supported_by_plan !== true) continue;
132
129
  const option = normalizeResetOption(credit);
133
- if (options.requireExplicitCredit && option.expiresAt !== undefined &&
130
+ if (option.expiresAt !== undefined &&
134
131
  option.expiresAt * 1_000 <= (options.now ?? Date.now())) continue;
135
132
  resetOptions.push(option);
136
133
  }
@@ -140,12 +137,7 @@ export function normalizeCodexResetCreditsPayload(
140
137
  (right.expiresAt ?? Number.MAX_SAFE_INTEGER),
141
138
  );
142
139
  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
- };
140
+ return { availableCount: resetOptions.length, options: resetOptions };
149
141
  }
150
142
 
151
143
  export function parseCodexResetOutcome(
@@ -207,7 +199,7 @@ function isOutcomeCode(value: unknown): value is CodexResetOutcomeCode {
207
199
  );
208
200
  }
209
201
 
210
- function codexAccountIdFromAccessToken(access: string): string | undefined {
202
+ export function codexAccountIdFromAccessToken(access: string): string | undefined {
211
203
  try {
212
204
  const parts = access.split(".");
213
205
  if (parts.length !== 3 || !parts[1]) return undefined;
@@ -41,15 +41,15 @@ export async function resolveCodexResetAuth(
41
41
  }
42
42
  const expectedModel = `${model.provider}/${model.id}`;
43
43
  const adapter = adapterForProvider(model.provider);
44
- if (!adapter) throw new Error("OpenAI Codex usage support is unavailable.");
44
+ if (!adapter) throw new Error(`Usage support for ${model.provider} is unavailable.`);
45
45
  const auth = await resolveUsageAuth(ctx, adapter, salt);
46
46
  if (`${ctx.model?.provider}/${ctx.model?.id}` !== expectedModel) {
47
47
  throw new Error(
48
- "The current model changed while resolving Codex reset authentication.",
48
+ "The current model changed while resolving reset authentication.",
49
49
  );
50
50
  }
51
51
  if (!auth)
52
- throw new Error("No runtime credential is configured for OpenAI Codex.");
52
+ throw new Error(`No runtime credential is configured for ${adapter.displayName}.`);
53
53
 
54
54
  const resolvedAccess =
55
55
  bearerToken(headerValue(auth.headers, "Authorization")) ?? auth.apiKey;
@@ -98,7 +98,6 @@ export async function listCodexResetCredits(
98
98
  timeoutMs,
99
99
  "Codex reset endpoint",
100
100
  ),
101
- { requireExplicitCredit: auth.actualProviderId === OPENAI_PROVIDER_ID },
102
101
  );
103
102
  }
104
103
 
@@ -111,8 +110,8 @@ export async function consumeCodexResetCredit(
111
110
  ): Promise<CodexResetOutcome> {
112
111
  if (!redeemRequestId)
113
112
  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.");
113
+ if (!option.creditId) {
114
+ throw new Error("Account resets require an explicitly selected credit.");
116
115
  }
117
116
  return parseCodexResetOutcome(
118
117
  await fetchProviderJson(
@@ -125,7 +124,7 @@ export async function consumeCodexResetCredit(
125
124
  method: "POST",
126
125
  body: {
127
126
  redeem_request_id: redeemRequestId,
128
- ...(option.creditId ? { credit_id: option.creditId } : {}),
127
+ credit_id: option.creditId,
129
128
  },
130
129
  },
131
130
  ),