@specode/pi-subscription-usage 1.3.1 → 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 +83 -85
- package/README.zh-CN.md +85 -87
- package/package.json +4 -3
- package/src/providers/antigravity.ts +372 -0
- package/src/query.ts +145 -6
- package/src/types.ts +1 -0
- package/src/usage.ts +10 -3
package/README.md
CHANGED
|
@@ -1,65 +1,99 @@
|
|
|
1
|
-
#
|
|
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
|
|
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
|
-
|
|
7
|
+
Footer status bar:
|
|
8
8
|
|
|
9
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
60
|
+
From npm:
|
|
21
61
|
|
|
22
62
|
```bash
|
|
23
|
-
pi install
|
|
63
|
+
pi install npm:@specode/pi-subscription-usage
|
|
24
64
|
```
|
|
25
65
|
|
|
26
|
-
|
|
66
|
+
From GitHub:
|
|
27
67
|
|
|
28
68
|
```bash
|
|
29
|
-
pi install
|
|
69
|
+
pi install git:github.com/specode/pi-subscription-usage
|
|
30
70
|
```
|
|
31
71
|
|
|
32
|
-
|
|
72
|
+
From a local directory for development:
|
|
33
73
|
|
|
34
74
|
```bash
|
|
35
|
-
pi install /
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
53
|
-
2. Model-specific sections
|
|
54
|
-
3. `Account`
|
|
85
|
+
### Reset Credits (OpenAI and Codex)
|
|
55
86
|
|
|
56
|
-
|
|
87
|
+
When your OpenAI or Codex account has redeemable rate-limit reset tickets, `/usage` offers to use one:
|
|
57
88
|
|
|
58
|
-
|
|
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
|
-
|
|
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
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
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 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
|
-
|
|
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
|
-
|
|
109
|
+
Run `/reload` after changing the config file. `displayMode` applies to the footer status bar, `/usage` progress bars, and status events.
|
|
96
110
|
|
|
97
|
-
##
|
|
111
|
+
## Privacy and Safety
|
|
98
112
|
|
|
99
|
-
-
|
|
100
|
-
-
|
|
101
|
-
-
|
|
102
|
-
-
|
|
103
|
-
-
|
|
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
|
-
|
|
125
|
+
# Check package contents
|
|
123
126
|
npm run pack:check
|
|
124
|
-
```
|
|
125
|
-
|
|
126
|
-
Load the extension directly without installing it:
|
|
127
127
|
|
|
128
|
-
|
|
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
|
-
|
|
133
|
-
|
|
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.
|
|
132
|
+
### Status Events for Theme and Extension Authors
|
|
135
133
|
|
|
136
|
-
|
|
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
|
|
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
|
-
#
|
|
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
|
-
|
|
5
|
+
一个 [Pi](https://github.com/earendil-works/pi-mono) 扩展:在底部状态栏显示当前订阅还剩多少额度,输入 `/usage` 查看完整明细。
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
底部状态栏效果:
|
|
8
8
|
|
|
9
|
-
|
|
9
|
+
```text
|
|
10
|
+
5h 99% ↻2h13m · 1w 85% ↻3d4h
|
|
11
|
+
```
|
|
10
12
|
|
|
11
|
-
|
|
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
|
-
|
|
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
|
-
|
|
33
|
+
登录方法:输入 `/login`,先选 `Sign in with an account`(下表记为 Account)或 `Sign in with an API key`(下表记为 API key),再在列表里选下表中的名称。Pi 界面只有英文,这里的选项名称都按界面原文写。
|
|
21
34
|
|
|
22
|
-
|
|
23
|
-
|
|
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
|
-
|
|
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 /
|
|
69
|
+
pi install git:github.com/specode/pi-subscription-usage
|
|
36
70
|
```
|
|
37
71
|
|
|
38
|
-
|
|
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
|
-
|
|
78
|
+
## 使用说明
|
|
79
|
+
|
|
80
|
+
按上面的方法登录,再选一个该提供商的模型,之后:
|
|
49
81
|
|
|
50
|
-
|
|
82
|
+
- 底部状态栏会自动显示当前额度窗口,在每轮对话结束后及每 5 分钟刷新一次(带 5 分钟缓存)。
|
|
83
|
+
- 执行 `/usage` 会跳过缓存直接拉取最新数据,显示进度条、重置时间(`MM/DD HH:mm`)及账号信息。
|
|
51
84
|
|
|
52
|
-
|
|
53
|
-
2. 各模型专属分组
|
|
54
|
-
3. `Account`
|
|
85
|
+
### 使用重置券(OpenAI 与 Codex)
|
|
55
86
|
|
|
56
|
-
|
|
87
|
+
OpenAI 或 Codex 账号里有可用的限额重置券时,`/usage` 会提供使用入口:
|
|
57
88
|
|
|
58
|
-
|
|
89
|
+
- 确认弹窗默认选中 `Cancel (Default)`,必须手动确认才会消耗重置券。
|
|
90
|
+
- 提交兑换前,扩展会检查当前模型和账号是否发生变动,并核对运行时令牌是否与 Pi 保存的 OAuth 登录信息一致。
|
|
91
|
+
- 在 OpenAI 模式下,重置券作用于服务端定义的账户级窗口,不一定单独清空当前应用的限额。
|
|
92
|
+
- 兑换重置券是本扩展唯一的写操作。
|
|
59
93
|
|
|
60
94
|
## 配置
|
|
61
95
|
|
|
62
|
-
|
|
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
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
该配置同时作用于底部状态、`/usage` 额度条和结构化状态事件。修改配置文件后运行 `/reload`。
|
|
76
|
-
|
|
77
|
-
## OpenAI / Codex 重置安全措施
|
|
78
|
-
|
|
79
|
-
OpenAI 与 Codex 模式都使用 ChatGPT 用量页相同的 `/wham/rate-limit-reset-credits` 和 `/consume` 接口,并以 Codex 账户的后端凭据认证;显示和兑换时都通过 `chatgpt-account-id` 限定为该令牌自身的账户。两种模式都只统计和提供明确存在、可用、套餐支持且未过期的 `codex_rate_limits` 票据,且始终指定具体票据兑换:仅有汇总次数或列表查询失败时,都不会退回由服务端选票的兑换。OpenAI 模式下,票据重置的是服务端定义的账户窗口,**不保证清空当前应用窗口**,确认框会说明这一范围。查询重置次数失败不会隐藏额度;兑换成功会使两种模式的额度缓存失效。
|
|
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
|
-
|
|
109
|
+
修改配置文件后执行 `/reload` 生效。`displayMode` 同时作用于底部状态栏、`/usage` 进度条和状态事件。
|
|
96
110
|
|
|
97
|
-
##
|
|
111
|
+
## 隐私与安全
|
|
98
112
|
|
|
99
|
-
-
|
|
100
|
-
-
|
|
101
|
-
-
|
|
102
|
-
-
|
|
103
|
-
-
|
|
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
|
-
|
|
125
|
+
# 检查打包文件列表
|
|
123
126
|
npm run pack:check
|
|
124
|
-
```
|
|
125
|
-
|
|
126
|
-
不安装、直接加载扩展:
|
|
127
127
|
|
|
128
|
-
|
|
128
|
+
# 不安装直接加载扩展验证
|
|
129
129
|
pi --no-extensions --offline -e ./index.ts --list-models
|
|
130
130
|
```
|
|
131
131
|
|
|
132
|
-
|
|
133
|
-
|
|
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 匹配不是对两套令牌身份的独立验签证明。
|
|
132
|
+
### 主题与状态栏扩展接入
|
|
135
133
|
|
|
136
|
-
|
|
134
|
+
扩展会在 `subscription-usage/status/v1` 事件通道发布结构化状态事件,供自定义主题或状态栏扩展直接渲染额度数据,无需解析状态栏文本。窗口固定按 `5h` -> `1w` -> `1m` -> 其他顺序排列;就绪事件包含 `displayMode`,每个窗口提供 `displayPercent`、`remainingPercent`、`usedPercent` 和 `resetCountdown`。
|
|
137
135
|
|
|
138
136
|
## 许可证
|
|
139
137
|
|
|
140
|
-
|
|
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.
|
|
4
|
-
"description": "Show subscription quota for OpenAI, Codex, OpenCode Go, Grok, and
|
|
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",
|
|
@@ -0,0 +1,372 @@
|
|
|
1
|
+
import { sanitizeDisplayText } from "../core.ts";
|
|
2
|
+
import type { UsageBucket, UsageMetric, UsageReport } from "../types.ts";
|
|
3
|
+
|
|
4
|
+
export const ANTIGRAVITY_PROVIDER_ID = "antigravity";
|
|
5
|
+
export const ANTIGRAVITY_DEFAULT_ENDPOINT = "https://daily-cloudcode-pa.googleapis.com";
|
|
6
|
+
export const ANTIGRAVITY_OFFICIAL_ORIGINS = [
|
|
7
|
+
"https://daily-cloudcode-pa.googleapis.com",
|
|
8
|
+
"https://daily-cloudcode-pa.sandbox.googleapis.com",
|
|
9
|
+
"https://cloudcode-pa.googleapis.com",
|
|
10
|
+
] as const;
|
|
11
|
+
|
|
12
|
+
export const ANTIGRAVITY_DEFAULT_GROUP_ID = "gemini-models";
|
|
13
|
+
export const ANTIGRAVITY_3P_GROUP_ID = "claude-and-gpt-models";
|
|
14
|
+
export const ANTIGRAVITY_ARGON_GROUP_ID = "gemini-argon";
|
|
15
|
+
|
|
16
|
+
export const ANTIGRAVITY_USER_AGENT =
|
|
17
|
+
process.env.ANTIGRAVITY_USER_AGENT ||
|
|
18
|
+
process.env.NOAGY_USER_AGENT ||
|
|
19
|
+
"antigravity/cli/1.4.0 (aidev_client; os_type=linux; arch=amd64; cl=982146307; auth_method=consumer)";
|
|
20
|
+
|
|
21
|
+
export const ANTIGRAVITY_LOAD_CODE_ASSIST_BODY = {
|
|
22
|
+
metadata: {
|
|
23
|
+
ideType: "ANTIGRAVITY",
|
|
24
|
+
platform: "PLATFORM_UNSPECIFIED",
|
|
25
|
+
pluginType: "GEMINI",
|
|
26
|
+
},
|
|
27
|
+
} as const;
|
|
28
|
+
|
|
29
|
+
export function antigravityRequestHeaders(): Record<string, string> {
|
|
30
|
+
return {
|
|
31
|
+
"User-Agent": ANTIGRAVITY_USER_AGENT,
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const ANTIGRAVITY_RETRYABLE_STATUSES = new Set([
|
|
36
|
+
403, 404, 429, 500, 502, 503, 504,
|
|
37
|
+
]);
|
|
38
|
+
|
|
39
|
+
export function antigravityQueryOrigins(baseUrl: string | undefined): string[] {
|
|
40
|
+
const origins: string[] = [];
|
|
41
|
+
const add = (origin: string) => {
|
|
42
|
+
if (
|
|
43
|
+
ANTIGRAVITY_OFFICIAL_ORIGINS.includes(
|
|
44
|
+
origin as (typeof ANTIGRAVITY_OFFICIAL_ORIGINS)[number],
|
|
45
|
+
) &&
|
|
46
|
+
!origins.includes(origin)
|
|
47
|
+
) {
|
|
48
|
+
origins.push(origin);
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
if (baseUrl) {
|
|
52
|
+
try {
|
|
53
|
+
add(new URL(baseUrl).origin);
|
|
54
|
+
} catch {
|
|
55
|
+
// A malformed model URL falls through to the official list.
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
for (const origin of ANTIGRAVITY_OFFICIAL_ORIGINS) add(origin);
|
|
59
|
+
return origins;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** HTTP failures carry `status`; network failures surface as fetch's TypeError. */
|
|
63
|
+
export function isRetryableAntigravityError(error: unknown): boolean {
|
|
64
|
+
if (error instanceof TypeError) return true;
|
|
65
|
+
const status = httpStatus(error);
|
|
66
|
+
return status !== undefined && ANTIGRAVITY_RETRYABLE_STATUSES.has(status);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Free-tier accounts cannot read the aggregate quota summary. */
|
|
70
|
+
export function isAntigravitySubscriptionRequired(error: unknown): boolean {
|
|
71
|
+
return (
|
|
72
|
+
httpStatus(error) === 403 &&
|
|
73
|
+
error instanceof Error &&
|
|
74
|
+
/SUBSCRIPTION_REQUIRED|(?:lack|missing)[^\n]*license/iu.test(error.message)
|
|
75
|
+
);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function httpStatus(error: unknown): number | undefined {
|
|
79
|
+
const status = (error as { status?: unknown } | null)?.status;
|
|
80
|
+
return typeof status === "number" ? status : undefined;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export function extractAntigravityAuth(
|
|
84
|
+
apiKey: string | undefined,
|
|
85
|
+
existingAuthHeader: string | undefined,
|
|
86
|
+
): { authorization?: string; token?: string; email?: string } {
|
|
87
|
+
const fromKey = apiKey ? parseCredentialMaterial(apiKey) : undefined;
|
|
88
|
+
const fromHeader =
|
|
89
|
+
!fromKey?.token && existingAuthHeader
|
|
90
|
+
? parseBearerCredential(existingAuthHeader)
|
|
91
|
+
: undefined;
|
|
92
|
+
const token = fromKey?.token ?? fromHeader?.token;
|
|
93
|
+
const email = fromKey?.email ?? fromHeader?.email;
|
|
94
|
+
if (!token) {
|
|
95
|
+
if (fromKey?.json || fromHeader?.json) return { email };
|
|
96
|
+
return { authorization: existingAuthHeader, email };
|
|
97
|
+
}
|
|
98
|
+
return { authorization: `Bearer ${token}`, token, email };
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export function emailFromAntigravityCredential(
|
|
102
|
+
credential: unknown,
|
|
103
|
+
): string | undefined {
|
|
104
|
+
const record = asObject(credential);
|
|
105
|
+
if (record?.type !== "oauth") return undefined;
|
|
106
|
+
return asEmail(record.email);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export function normalizeAntigravityUsage(
|
|
110
|
+
payload: unknown,
|
|
111
|
+
capturedAt: number,
|
|
112
|
+
planPayload?: unknown,
|
|
113
|
+
accountEmail?: string,
|
|
114
|
+
): UsageReport {
|
|
115
|
+
const root = asObject(payload);
|
|
116
|
+
if (!root || !Array.isArray(root.groups)) {
|
|
117
|
+
throw new Error("Antigravity usage response was not an object.");
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const buckets: UsageBucket[] = [];
|
|
121
|
+
for (const rawGroup of root.groups) {
|
|
122
|
+
const group = asObject(rawGroup);
|
|
123
|
+
if (!group) continue;
|
|
124
|
+
const classification = classifyGroup(group);
|
|
125
|
+
const rawBuckets = Array.isArray(group.buckets) ? group.buckets : [];
|
|
126
|
+
for (const rawBucket of rawBuckets) {
|
|
127
|
+
const b = asObject(rawBucket);
|
|
128
|
+
if (!b) continue;
|
|
129
|
+
const remainingFraction = asNumber(b.remainingFraction);
|
|
130
|
+
if (remainingFraction === undefined) continue;
|
|
131
|
+
|
|
132
|
+
const clampedFraction = Math.min(1, Math.max(0, remainingFraction));
|
|
133
|
+
const remaining = clampPercent(roundPercent(clampedFraction * 100));
|
|
134
|
+
const used = clampPercent(roundPercent(100 - remaining));
|
|
135
|
+
|
|
136
|
+
const bucketId =
|
|
137
|
+
asString(b.bucketId) || asString(b.displayName) || "bucket";
|
|
138
|
+
const windowMinutes = parseWindowMinutes(b.window, bucketId);
|
|
139
|
+
const resetsAt = asEpochSeconds(b.resetTime);
|
|
140
|
+
const label = asString(b.displayName) || "Limit";
|
|
141
|
+
|
|
142
|
+
buckets.push({
|
|
143
|
+
id: `${classification.groupId}:${bucketId}`,
|
|
144
|
+
label,
|
|
145
|
+
groupId: classification.groupId,
|
|
146
|
+
groupLabel: classification.groupLabel,
|
|
147
|
+
modelKeys: classification.modelKeys,
|
|
148
|
+
used,
|
|
149
|
+
remaining,
|
|
150
|
+
limit: 100,
|
|
151
|
+
unit: "percent",
|
|
152
|
+
...(windowMinutes !== undefined ? { windowMinutes } : {}),
|
|
153
|
+
...(resetsAt !== undefined ? { resetsAt } : {}),
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
if (buckets.length === 0) {
|
|
159
|
+
throw new Error(
|
|
160
|
+
"Antigravity usage endpoint returned no displayable usage data.",
|
|
161
|
+
);
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
const metrics: UsageMetric[] = [];
|
|
165
|
+
const email = asEmail(accountEmail);
|
|
166
|
+
if (email) {
|
|
167
|
+
metrics.push({ id: "email", label: "Email", value: email });
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
const plan = extractPlanName(planPayload);
|
|
171
|
+
if (plan) {
|
|
172
|
+
metrics.push({ id: "plan", label: "Plan", value: plan });
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
const project = extractProject(planPayload);
|
|
176
|
+
if (project) {
|
|
177
|
+
metrics.push({ id: "project", label: "Project", value: project });
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
const defaultGroupId = buckets.some(
|
|
181
|
+
(b) => b.groupId === ANTIGRAVITY_DEFAULT_GROUP_ID,
|
|
182
|
+
)
|
|
183
|
+
? ANTIGRAVITY_DEFAULT_GROUP_ID
|
|
184
|
+
: buckets[0]?.groupId;
|
|
185
|
+
|
|
186
|
+
return {
|
|
187
|
+
providerId: ANTIGRAVITY_PROVIDER_ID,
|
|
188
|
+
providerName: "Antigravity",
|
|
189
|
+
capturedAt,
|
|
190
|
+
source: "antigravity-quota",
|
|
191
|
+
semantics: {
|
|
192
|
+
kind: "consumer-subscription",
|
|
193
|
+
label: "Antigravity subscription limits",
|
|
194
|
+
},
|
|
195
|
+
defaultGroupId,
|
|
196
|
+
buckets,
|
|
197
|
+
metrics,
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
function classifyGroup(group: Record<string, unknown>): {
|
|
202
|
+
groupId: string;
|
|
203
|
+
groupLabel: string;
|
|
204
|
+
modelKeys: string[];
|
|
205
|
+
} {
|
|
206
|
+
const displayName = asString(group.displayName) ?? "";
|
|
207
|
+
const rawBuckets = Array.isArray(group.buckets) ? group.buckets : [];
|
|
208
|
+
const bucketIds = rawBuckets
|
|
209
|
+
.map((b) => asString(asObject(b)?.bucketId)?.toLowerCase() ?? "")
|
|
210
|
+
.filter(Boolean);
|
|
211
|
+
|
|
212
|
+
if (bucketIds.some((id) => id.includes("argon"))) {
|
|
213
|
+
return {
|
|
214
|
+
groupId: ANTIGRAVITY_ARGON_GROUP_ID,
|
|
215
|
+
groupLabel: displayName || "Gemini 4 Argon",
|
|
216
|
+
modelKeys: ["argon", "gemini-4-argon"],
|
|
217
|
+
};
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
if (
|
|
221
|
+
bucketIds.some(
|
|
222
|
+
(id) => id.startsWith("3p") || id.includes("claude") || id.includes("gpt"),
|
|
223
|
+
)
|
|
224
|
+
) {
|
|
225
|
+
return {
|
|
226
|
+
groupId: ANTIGRAVITY_3P_GROUP_ID,
|
|
227
|
+
groupLabel: displayName || "Claude and GPT models",
|
|
228
|
+
modelKeys: ["claude", "gpt-oss"],
|
|
229
|
+
};
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
if (bucketIds.some((id) => id.includes("gemini"))) {
|
|
233
|
+
return {
|
|
234
|
+
groupId: ANTIGRAVITY_DEFAULT_GROUP_ID,
|
|
235
|
+
groupLabel: displayName || "Gemini Models",
|
|
236
|
+
modelKeys: ["gemini-flash", "gemini-pro", "gemini"],
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
const fallbackSlug =
|
|
241
|
+
displayName
|
|
242
|
+
.toLowerCase()
|
|
243
|
+
.replace(/[^a-z0-9]+/gu, "-")
|
|
244
|
+
.replace(/^-+|-+$/gu, "") || "other";
|
|
245
|
+
|
|
246
|
+
return {
|
|
247
|
+
groupId: fallbackSlug,
|
|
248
|
+
groupLabel: displayName || "Other Models",
|
|
249
|
+
modelKeys: [fallbackSlug],
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
function parseWindowMinutes(
|
|
254
|
+
windowValue: unknown,
|
|
255
|
+
bucketId: string,
|
|
256
|
+
): number | undefined {
|
|
257
|
+
const str = asString(windowValue)?.toLowerCase();
|
|
258
|
+
if (str === "weekly" || str === "1w" || str === "week") return 10_080;
|
|
259
|
+
if (str === "monthly" || str === "1m" || str === "month") return 43_200;
|
|
260
|
+
if (str === "5h") return 300;
|
|
261
|
+
if (str) {
|
|
262
|
+
const hourMatch = /^(\d+)\s*h$/iu.exec(str);
|
|
263
|
+
if (hourMatch) return Number.parseInt(hourMatch[1], 10) * 60;
|
|
264
|
+
const dayMatch = /^(\d+)\s*d$/iu.exec(str);
|
|
265
|
+
if (dayMatch) return Number.parseInt(dayMatch[1], 10) * 1_440;
|
|
266
|
+
const minMatch = /^(\d+)\s*m$/iu.exec(str);
|
|
267
|
+
if (minMatch) return Number.parseInt(minMatch[1], 10);
|
|
268
|
+
}
|
|
269
|
+
const id = bucketId.toLowerCase();
|
|
270
|
+
if (id.includes("5h")) return 300;
|
|
271
|
+
if (id.includes("weekly") || id.includes("1w")) return 10_080;
|
|
272
|
+
if (id.includes("monthly") || id.includes("1m")) return 43_200;
|
|
273
|
+
return undefined;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
function extractPlanName(planPayload: unknown): string | undefined {
|
|
277
|
+
const root = asObject(planPayload);
|
|
278
|
+
if (!root) return undefined;
|
|
279
|
+
const paidTier = asObject(root.paidTier);
|
|
280
|
+
const paidName = asString(paidTier?.name);
|
|
281
|
+
if (paidName) return paidName;
|
|
282
|
+
const currentTier = asObject(root.currentTier);
|
|
283
|
+
const currentName = asString(currentTier?.name);
|
|
284
|
+
if (currentName) return currentName;
|
|
285
|
+
return undefined;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
function extractProject(planPayload: unknown): string | undefined {
|
|
289
|
+
const root = asObject(planPayload);
|
|
290
|
+
if (!root) return undefined;
|
|
291
|
+
return asString(root.cloudaicompanionProject);
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
function parseCredentialMaterial(value: string): {
|
|
295
|
+
token?: string;
|
|
296
|
+
email?: string;
|
|
297
|
+
json: boolean;
|
|
298
|
+
} {
|
|
299
|
+
const trimmed = value.trim();
|
|
300
|
+
const json = trimmed.startsWith("{") && trimmed.endsWith("}");
|
|
301
|
+
if (!json) return { token: trimmed || undefined, json: false };
|
|
302
|
+
try {
|
|
303
|
+
const parsed = JSON.parse(trimmed) as {
|
|
304
|
+
token?: unknown;
|
|
305
|
+
access?: unknown;
|
|
306
|
+
email?: unknown;
|
|
307
|
+
};
|
|
308
|
+
const token =
|
|
309
|
+
typeof parsed.token === "string" && parsed.token.trim()
|
|
310
|
+
? parsed.token.trim()
|
|
311
|
+
: typeof parsed.access === "string" && parsed.access.trim()
|
|
312
|
+
? parsed.access.trim()
|
|
313
|
+
: undefined;
|
|
314
|
+
const email =
|
|
315
|
+
typeof parsed.email === "string" && parsed.email.trim()
|
|
316
|
+
? parsed.email.trim()
|
|
317
|
+
: undefined;
|
|
318
|
+
return { token, email, json: true };
|
|
319
|
+
} catch {
|
|
320
|
+
return { json: true };
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
function parseBearerCredential(header: string): {
|
|
325
|
+
token?: string;
|
|
326
|
+
email?: string;
|
|
327
|
+
json: boolean;
|
|
328
|
+
} | undefined {
|
|
329
|
+
const match = /^Bearer\s+(\S.*)$/iu.exec(header.trim());
|
|
330
|
+
return match ? parseCredentialMaterial(match[1]) : undefined;
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
function asObject(value: unknown): Record<string, unknown> | undefined {
|
|
334
|
+
return value && typeof value === "object" && !Array.isArray(value)
|
|
335
|
+
? (value as Record<string, unknown>)
|
|
336
|
+
: undefined;
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
function asString(value: unknown): string | undefined {
|
|
340
|
+
return typeof value === "string"
|
|
341
|
+
? sanitizeDisplayText(value, 160) || undefined
|
|
342
|
+
: undefined;
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
function asNumber(value: unknown): number | undefined {
|
|
346
|
+
if (typeof value === "number" && Number.isFinite(value)) return value;
|
|
347
|
+
if (typeof value === "string" && value.trim()) {
|
|
348
|
+
const parsed = Number(value);
|
|
349
|
+
return Number.isFinite(parsed) ? parsed : undefined;
|
|
350
|
+
}
|
|
351
|
+
return undefined;
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
function asEmail(value: unknown): string | undefined {
|
|
355
|
+
if (typeof value !== "string" || value.length > 254) return undefined;
|
|
356
|
+
const email = sanitizeDisplayText(value, 254).toLowerCase();
|
|
357
|
+
return /^[^\s@]+@[^\s@]+$/u.test(email) ? email : undefined;
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
function asEpochSeconds(value: unknown): number | undefined {
|
|
361
|
+
if (typeof value !== "string" || !value.trim()) return undefined;
|
|
362
|
+
const parsed = Date.parse(value);
|
|
363
|
+
return Number.isNaN(parsed) ? undefined : Math.floor(parsed / 1000);
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
function clampPercent(value: number): number {
|
|
367
|
+
return Math.min(100, Math.max(0, value));
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
function roundPercent(value: number): number {
|
|
371
|
+
return Math.round(value * 1_000_000) / 1_000_000;
|
|
372
|
+
}
|
package/src/query.ts
CHANGED
|
@@ -9,6 +9,18 @@ import {
|
|
|
9
9
|
redactUsageError,
|
|
10
10
|
} from "./core.ts";
|
|
11
11
|
import { CODEX_PROVIDER_ID } from "./providers/codex-constants.ts";
|
|
12
|
+
import {
|
|
13
|
+
ANTIGRAVITY_LOAD_CODE_ASSIST_BODY,
|
|
14
|
+
ANTIGRAVITY_OFFICIAL_ORIGINS,
|
|
15
|
+
ANTIGRAVITY_PROVIDER_ID,
|
|
16
|
+
antigravityQueryOrigins,
|
|
17
|
+
antigravityRequestHeaders,
|
|
18
|
+
emailFromAntigravityCredential,
|
|
19
|
+
extractAntigravityAuth,
|
|
20
|
+
isAntigravitySubscriptionRequired,
|
|
21
|
+
isRetryableAntigravityError,
|
|
22
|
+
normalizeAntigravityUsage,
|
|
23
|
+
} from "./providers/antigravity.ts";
|
|
12
24
|
import {
|
|
13
25
|
codexAccountIdFromAccessToken,
|
|
14
26
|
normalizeCodexResetCreditsPayload,
|
|
@@ -206,8 +218,112 @@ export const SUPPORTED_ADAPTERS: readonly UsageProviderAdapter[] = [
|
|
|
206
218
|
return normalizeGrokBilling(credits, capturedAt, monthly);
|
|
207
219
|
},
|
|
208
220
|
},
|
|
221
|
+
{
|
|
222
|
+
id: ANTIGRAVITY_PROVIDER_ID,
|
|
223
|
+
displayName: "Antigravity",
|
|
224
|
+
providerIds: [ANTIGRAVITY_PROVIDER_ID],
|
|
225
|
+
officialOrigins: ANTIGRAVITY_OFFICIAL_ORIGINS,
|
|
226
|
+
semantics: {
|
|
227
|
+
kind: "consumer-subscription",
|
|
228
|
+
label: "Antigravity subscription limits",
|
|
229
|
+
},
|
|
230
|
+
async query(auth, signal, timeoutMs) {
|
|
231
|
+
const origins = antigravityQueryOrigins(auth.model?.baseUrl);
|
|
232
|
+
// Plan metadata is optional; attach the handler now so a quota failure
|
|
233
|
+
// cannot leave this request as an unhandled rejection.
|
|
234
|
+
const plan = fetchAntigravityJson(
|
|
235
|
+
origins,
|
|
236
|
+
"/v1internal:loadCodeAssist",
|
|
237
|
+
auth,
|
|
238
|
+
signal,
|
|
239
|
+
timeoutMs,
|
|
240
|
+
"Antigravity code assist endpoint",
|
|
241
|
+
ANTIGRAVITY_LOAD_CODE_ASSIST_BODY,
|
|
242
|
+
).then(
|
|
243
|
+
(result) => result.payload,
|
|
244
|
+
() => undefined,
|
|
245
|
+
);
|
|
246
|
+
const quota = await fetchAntigravityJson(
|
|
247
|
+
origins,
|
|
248
|
+
"/v1internal:retrieveUserQuotaSummary",
|
|
249
|
+
auth,
|
|
250
|
+
signal,
|
|
251
|
+
timeoutMs,
|
|
252
|
+
"Antigravity quota endpoint",
|
|
253
|
+
{},
|
|
254
|
+
);
|
|
255
|
+
const planPayload = await plan;
|
|
256
|
+
if (signal.aborted) {
|
|
257
|
+
throw Object.assign(new Error("Usage query aborted."), {
|
|
258
|
+
name: "AbortError",
|
|
259
|
+
});
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
return normalizeAntigravityUsage(
|
|
263
|
+
quota.payload,
|
|
264
|
+
Date.now(),
|
|
265
|
+
planPayload,
|
|
266
|
+
auth.accountEmail,
|
|
267
|
+
);
|
|
268
|
+
},
|
|
269
|
+
},
|
|
209
270
|
];
|
|
210
271
|
|
|
272
|
+
async function readAntigravityStoredCredential(): Promise<unknown> {
|
|
273
|
+
try {
|
|
274
|
+
const { readStoredCredential } = await import(
|
|
275
|
+
"@earendil-works/pi-coding-agent",
|
|
276
|
+
);
|
|
277
|
+
return readStoredCredential(ANTIGRAVITY_PROVIDER_ID);
|
|
278
|
+
} catch {
|
|
279
|
+
return undefined;
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
async function fetchAntigravityJson(
|
|
284
|
+
origins: readonly string[],
|
|
285
|
+
path: string,
|
|
286
|
+
auth: ResolvedUsageAuth,
|
|
287
|
+
signal: AbortSignal,
|
|
288
|
+
timeoutMs: number,
|
|
289
|
+
description: string,
|
|
290
|
+
body: Record<string, unknown>,
|
|
291
|
+
): Promise<{ origin: string; payload: Record<string, unknown> }> {
|
|
292
|
+
let lastError: unknown;
|
|
293
|
+
for (const origin of origins) {
|
|
294
|
+
try {
|
|
295
|
+
return {
|
|
296
|
+
origin,
|
|
297
|
+
payload: await fetchProviderJson(
|
|
298
|
+
`${origin}${path}`,
|
|
299
|
+
auth,
|
|
300
|
+
signal,
|
|
301
|
+
timeoutMs,
|
|
302
|
+
description,
|
|
303
|
+
{
|
|
304
|
+
method: "POST",
|
|
305
|
+
body,
|
|
306
|
+
headers: antigravityRequestHeaders(),
|
|
307
|
+
},
|
|
308
|
+
),
|
|
309
|
+
};
|
|
310
|
+
} catch (error) {
|
|
311
|
+
if (isAbortError(error) || signal.aborted) throw error;
|
|
312
|
+
// Free-tier accounts get this on every origin; it is not a fault.
|
|
313
|
+
if (isAntigravitySubscriptionRequired(error)) {
|
|
314
|
+
throw new UsageUnsupportedError(
|
|
315
|
+
"Antigravity quota summary requires a paid Google AI subscription.",
|
|
316
|
+
);
|
|
317
|
+
}
|
|
318
|
+
lastError = error;
|
|
319
|
+
if (!isRetryableAntigravityError(error)) throw error;
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
throw lastError instanceof Error
|
|
323
|
+
? lastError
|
|
324
|
+
: new Error(`${description} failed.`);
|
|
325
|
+
}
|
|
326
|
+
|
|
211
327
|
export function adapterForProvider(
|
|
212
328
|
providerId: string | undefined,
|
|
213
329
|
): UsageProviderAdapter | undefined {
|
|
@@ -265,13 +381,28 @@ export async function resolveUsageAuth(
|
|
|
265
381
|
`${adapter.displayName} usage cannot send a proxy-resolved credential to an official usage endpoint.`,
|
|
266
382
|
);
|
|
267
383
|
}
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
384
|
+
let authorization = headerValue(result.auth.headers, "Authorization");
|
|
385
|
+
let extractedToken: string | undefined;
|
|
386
|
+
let accountEmail: string | undefined;
|
|
387
|
+
|
|
388
|
+
if (adapter.id === ANTIGRAVITY_PROVIDER_ID) {
|
|
389
|
+
const extracted = extractAntigravityAuth(result.auth.apiKey, authorization);
|
|
390
|
+
authorization = extracted.authorization;
|
|
391
|
+
extractedToken = extracted.token;
|
|
392
|
+
accountEmail =
|
|
393
|
+
extracted.email ??
|
|
394
|
+
emailFromAntigravityCredential(
|
|
395
|
+
await readAntigravityStoredCredential(),
|
|
396
|
+
);
|
|
397
|
+
} else if (!authorization && result.auth.apiKey) {
|
|
398
|
+
authorization = `Bearer ${result.auth.apiKey}`;
|
|
399
|
+
}
|
|
400
|
+
|
|
271
401
|
if (!authorization) return undefined;
|
|
272
402
|
const headers = { Authorization: authorization };
|
|
273
403
|
const secrets = [
|
|
274
404
|
result.auth.apiKey,
|
|
405
|
+
extractedToken && extractedToken !== result.auth.apiKey ? extractedToken : undefined,
|
|
275
406
|
headerValue(result.auth.headers, "Authorization"),
|
|
276
407
|
authorization,
|
|
277
408
|
].filter((value): value is string => Boolean(value));
|
|
@@ -287,6 +418,7 @@ export async function resolveUsageAuth(
|
|
|
287
418
|
actualProviderId: model.provider,
|
|
288
419
|
model,
|
|
289
420
|
openaiClientId: clientId,
|
|
421
|
+
accountEmail,
|
|
290
422
|
// Only the backend credential is sent to ChatGPT. The active API token
|
|
291
423
|
// is used locally for registration matching and cache invalidation.
|
|
292
424
|
headers: companion.headers,
|
|
@@ -296,6 +428,7 @@ export async function resolveUsageAuth(
|
|
|
296
428
|
}
|
|
297
429
|
return {
|
|
298
430
|
actualProviderId: model.provider,
|
|
431
|
+
accountEmail,
|
|
299
432
|
apiKey: result.auth.apiKey,
|
|
300
433
|
headers,
|
|
301
434
|
fingerprint: fingerprintResolvedAuth({ headers }, salt),
|
|
@@ -345,7 +478,10 @@ export async function queryProviderUsage(
|
|
|
345
478
|
return await adapter.query(auth, signal, timeoutMs);
|
|
346
479
|
} catch (error) {
|
|
347
480
|
if (error instanceof Error && error.name === "AbortError") throw error;
|
|
348
|
-
|
|
481
|
+
const message = redactUsageError(errorMessage(error), auth.secrets);
|
|
482
|
+
throw error instanceof UsageUnsupportedError
|
|
483
|
+
? new UsageUnsupportedError(message)
|
|
484
|
+
: new Error(message);
|
|
349
485
|
}
|
|
350
486
|
}
|
|
351
487
|
|
|
@@ -392,8 +528,11 @@ export async function fetchProviderJson(
|
|
|
392
528
|
description,
|
|
393
529
|
);
|
|
394
530
|
if (!response.ok) {
|
|
395
|
-
throw
|
|
396
|
-
|
|
531
|
+
throw Object.assign(
|
|
532
|
+
new Error(
|
|
533
|
+
`${description} returned ${response.status} ${response.statusText}: ${redactUsageError(text, auth.secrets)}`,
|
|
534
|
+
),
|
|
535
|
+
{ status: response.status },
|
|
397
536
|
);
|
|
398
537
|
}
|
|
399
538
|
let parsed: unknown;
|
package/src/types.ts
CHANGED
|
@@ -53,6 +53,7 @@ export interface ResolvedUsageAuth {
|
|
|
53
53
|
openaiClientId?: string;
|
|
54
54
|
/** Original usage identity, retained when reset auth adds account headers. */
|
|
55
55
|
usageFingerprint?: string;
|
|
56
|
+
accountEmail?: string;
|
|
56
57
|
apiKey?: string;
|
|
57
58
|
headers: Record<string, string>;
|
|
58
59
|
fingerprint: string;
|
package/src/usage.ts
CHANGED
|
@@ -69,7 +69,10 @@ type StableCurrent = {
|
|
|
69
69
|
|
|
70
70
|
export default function subscriptionUsage(pi: ExtensionAPI): void {
|
|
71
71
|
const cache = new UsageCache(CACHE_TTL_MS);
|
|
72
|
-
const failureBackoff = new Map<
|
|
72
|
+
const failureBackoff = new Map<
|
|
73
|
+
string,
|
|
74
|
+
{ until: number; message: string; status: "unsupported" | "query-failed" }
|
|
75
|
+
>();
|
|
73
76
|
const activeControllers = new Set<AbortController>();
|
|
74
77
|
let sessionActive = false;
|
|
75
78
|
let displayMode: UsageDisplayMode = DEFAULT_USAGE_DISPLAY_MODE;
|
|
@@ -224,7 +227,7 @@ export default function subscriptionUsage(pi: ExtensionAPI): void {
|
|
|
224
227
|
state: {
|
|
225
228
|
providerId: adapter.id,
|
|
226
229
|
providerName: adapter.displayName,
|
|
227
|
-
status:
|
|
230
|
+
status: failure.status,
|
|
228
231
|
message: failure.message,
|
|
229
232
|
},
|
|
230
233
|
fingerprint: auth.fingerprint,
|
|
@@ -251,15 +254,19 @@ export default function subscriptionUsage(pi: ExtensionAPI): void {
|
|
|
251
254
|
} catch (error) {
|
|
252
255
|
if (isAbortError(error) || !sessionActive) throw error;
|
|
253
256
|
const message = errorMessage(error);
|
|
257
|
+
const status = error instanceof UsageUnsupportedError
|
|
258
|
+
? "unsupported"
|
|
259
|
+
: "query-failed";
|
|
254
260
|
failureBackoff.set(failureKey, {
|
|
255
261
|
until: Date.now() + FAILURE_BACKOFF_MS,
|
|
256
262
|
message,
|
|
263
|
+
status,
|
|
257
264
|
});
|
|
258
265
|
return {
|
|
259
266
|
state: {
|
|
260
267
|
providerId: adapter.id,
|
|
261
268
|
providerName: adapter.displayName,
|
|
262
|
-
status
|
|
269
|
+
status,
|
|
263
270
|
message,
|
|
264
271
|
},
|
|
265
272
|
fingerprint: auth.fingerprint,
|