@specode/pi-subscription-usage 1.4.0 → 2.0.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 +20 -4
- package/README.zh-CN.md +20 -4
- package/package.json +3 -3
- package/src/format.ts +1 -0
- package/src/providers/claude-bridge.ts +118 -0
- package/src/query.ts +6 -145
- package/src/types.ts +2 -2
- package/src/usage.ts +54 -13
- package/src/providers/antigravity.ts +0 -372
package/README.md
CHANGED
|
@@ -39,7 +39,7 @@ To sign in, run `/login`, pick `Sign in with an account` (Account below) or `Sig
|
|
|
39
39
|
| OpenCode Go | API key → `OpenCode Go` | `5h`, `1w`, `1m` | — | |
|
|
40
40
|
| xAI Grok | Account → `xAI` | `1w` and/or `1m` | — | |
|
|
41
41
|
| Kimi Coding | Account → `Kimi For Coding` | `5h`, `1w`, membership level | — | |
|
|
42
|
-
|
|
|
42
|
+
| Claude (Claude Code) | None; signed in through Claude Code | `5h`, `1w` | — | [`pi-claude-bridge`](https://www.npmjs.com/package/pi-claude-bridge) 0.9.3 or later |
|
|
43
43
|
|
|
44
44
|
### Provider Notes
|
|
45
45
|
|
|
@@ -51,9 +51,24 @@ Sign in to both `OpenAI` and `OpenAI Codex (legacy)` with the same ChatGPT accou
|
|
|
51
51
|
|
|
52
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
53
|
|
|
54
|
-
####
|
|
54
|
+
#### Claude (Claude Code)
|
|
55
55
|
|
|
56
|
-
|
|
56
|
+
Requires [`pi-claude-bridge`](https://www.npmjs.com/package/pi-claude-bridge) by elidickinson ([GitHub](https://github.com/elidickinson/pi-claude-bridge)), version 0.9.3 or later. 0.9.3 is the first version that passes Claude Code's usage reports on to Pi. Install it with `pi install npm:pi-claude-bridge` and sign in to Claude Code itself; there is no Pi login. Usage covers models under the `claude-bridge` provider.
|
|
57
|
+
|
|
58
|
+
The bridge has no usage endpoint to query: Claude Code attaches your plan usage to its responses, and the extension reads that report. So the footer stays empty in each new session until the first report arrives, `/usage` shows the last reported values with the time they were reported instead of fetching, and a window whose reset time has passed shows as unused until the next report. The extension never reads Claude Code's credentials.
|
|
59
|
+
|
|
60
|
+
Tested with `pi-claude-bridge` 0.9.3 and Claude Code 2.1.311, the version bundled with the bridge's Agent SDK. If you point the bridge at your own `claude` executable (`pathToClaudeCodeExecutable`), older Claude Code versions are untested.
|
|
61
|
+
|
|
62
|
+
Several packages have similar names. The extension recognizes the `claude-bridge` provider id, so the package must both register that id and pass usage reports on. As of October 31, 2026:
|
|
63
|
+
|
|
64
|
+
| Package | Result |
|
|
65
|
+
| --- | --- |
|
|
66
|
+
| `pi-claude-bridge` 0.9.3 or later | Works |
|
|
67
|
+
| `@viniciosrab/pi-claude-bridge` 0.9.4-fork.3 | Same usage code as 0.9.3; expected to work, untested |
|
|
68
|
+
| `pi-claude-bridge` before 0.9.3, `@fractaal/pi-claude-bridge`, `@yassimba/pi-claude-bridge`, `@agimon-ai/po-claude-bridge` | Register `claude-bridge` but never pass usage on: the footer stays empty and `/usage` keeps showing `Waiting` |
|
|
69
|
+
| `@vanillagreen/pi-claude-bridge`, `pi-claude-subscription`, `pi-claude-directsdk`, `@ramtinj95/pi-claude-delegation` | Register a different provider id; not supported |
|
|
70
|
+
|
|
71
|
+
The npm package `claude-bridge`, without the `pi-` prefix, is an unrelated proxy server for the Claude Code CLI; `pi install npm:claude-bridge` installs the wrong package. Run `pi list` to check which package you have.
|
|
57
72
|
|
|
58
73
|
## Installation
|
|
59
74
|
|
|
@@ -81,6 +96,7 @@ Sign in through `/login` as described above, then select a model from that provi
|
|
|
81
96
|
|
|
82
97
|
- The footer status bar shows the active quota windows and refreshes after each turn and every 5 minutes (using a 5-minute cache).
|
|
83
98
|
- Running `/usage` always fetches fresh data for the active provider and shows progress bars, reset times (`MM/DD HH:mm`), and account details.
|
|
99
|
+
- Claude is the exception: its quota is never fetched, only read from Claude Code's responses (see [Claude (Claude Code)](#claude-claude-code)).
|
|
84
100
|
|
|
85
101
|
### Reset Credits (OpenAI and Codex)
|
|
86
102
|
|
|
@@ -110,7 +126,7 @@ Run `/reload` after changing the config file. `displayMode` applies to the foote
|
|
|
110
126
|
|
|
111
127
|
## Privacy and Safety
|
|
112
128
|
|
|
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
|
|
129
|
+
- 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`, and Claude usage comes from the bridge's responses, not Claude Code's keychain entry).
|
|
114
130
|
- Requests go only to each provider's official endpoints. Custom proxies and custom base URLs are refused.
|
|
115
131
|
- Tokens are never written to caches, session files, the status bar, or error messages.
|
|
116
132
|
- The extension does not modify model requests.
|
package/README.zh-CN.md
CHANGED
|
@@ -39,7 +39,7 @@ OpenAI Codex
|
|
|
39
39
|
| OpenCode Go | API key → `OpenCode Go` | `5h`、`1w`、`1m` | — | |
|
|
40
40
|
| xAI Grok | Account → `xAI` | `1w` 和/或 `1m` | — | |
|
|
41
41
|
| Kimi Coding | Account → `Kimi For Coding` | `5h`、`1w`、会员等级 | — | |
|
|
42
|
-
|
|
|
42
|
+
| Claude (Claude Code) | 无需在 Pi 登录,使用 Claude Code 的登录 | `5h`、`1w` | — | [`pi-claude-bridge`](https://www.npmjs.com/package/pi-claude-bridge) 0.9.3 及以上 |
|
|
43
43
|
|
|
44
44
|
### 提供商说明
|
|
45
45
|
|
|
@@ -51,9 +51,24 @@ OpenAI Codex
|
|
|
51
51
|
|
|
52
52
|
用 SuperGrok 账号登录(Account → `xAI`)。用 xAI 的 API Key 登录看不到订阅额度。如果你装的是第三方扩展 `pi-xai-oauth`,用它登录也可以。
|
|
53
53
|
|
|
54
|
-
####
|
|
54
|
+
#### Claude (Claude Code)
|
|
55
55
|
|
|
56
|
-
|
|
56
|
+
需要 elidickinson 发布的 [`pi-claude-bridge`](https://www.npmjs.com/package/pi-claude-bridge)([GitHub](https://github.com/elidickinson/pi-claude-bridge))0.9.3 及以上版本,0.9.3 是第一个把 Claude Code 的用量数据转交给 Pi 的版本。用 `pi install npm:pi-claude-bridge` 安装,并在 Claude Code 里登录,Pi 这边不用登录。这里指 `claude-bridge` 提供商下的模型。
|
|
57
|
+
|
|
58
|
+
bridge 没有可查询的用量接口:Claude Code 会在回复中附带当前套餐用量,扩展读取的就是这份数据。因此每个新会话要等收到第一份用量数据,底部状态栏才有内容;`/usage` 不会重新查询,只显示最近一次收到的数值和对应时间;如果某个窗口的重置时间已过,在收到下一份数据之前按未使用显示。扩展不会读取 Claude Code 的凭据。
|
|
59
|
+
|
|
60
|
+
已用 `pi-claude-bridge` 0.9.3 和 Claude Code 2.1.311(bridge 所带 Agent SDK 内置的版本)测试。如果你让 bridge 改用自己安装的 `claude` 可执行文件(`pathToClaudeCodeExecutable`),较旧的 Claude Code 版本未经测试。
|
|
61
|
+
|
|
62
|
+
npm 上有好几个名字相近的包。扩展按 `claude-bridge` 这个 provider id 识别,所以所用的包既要注册这个 id,也要转交用量数据。截至 2026 年 10 月 31 日:
|
|
63
|
+
|
|
64
|
+
| 包 | 结果 |
|
|
65
|
+
| --- | --- |
|
|
66
|
+
| `pi-claude-bridge` 0.9.3 及以上 | 可用 |
|
|
67
|
+
| `@viniciosrab/pi-claude-bridge` 0.9.4-fork.3 | 用量相关代码与 0.9.3 相同,预计可用,未测试 |
|
|
68
|
+
| `pi-claude-bridge` 0.9.3 以前的版本、`@fractaal/pi-claude-bridge`、`@yassimba/pi-claude-bridge`、`@agimon-ai/po-claude-bridge` | 注册了 `claude-bridge`,但不转交用量:底部状态栏一直为空,`/usage` 一直显示 `Waiting` |
|
|
69
|
+
| `@vanillagreen/pi-claude-bridge`、`pi-claude-subscription`、`pi-claude-directsdk`、`@ramtinj95/pi-claude-delegation` | 注册的是别的 provider id,不支持 |
|
|
70
|
+
|
|
71
|
+
不带 `pi-` 前缀的 npm 包 `claude-bridge` 是一个与此无关的 Claude Code CLI 代理服务器,`pi install npm:claude-bridge` 会装错包。可以用 `pi list` 确认装的是哪个。
|
|
57
72
|
|
|
58
73
|
## 安装
|
|
59
74
|
|
|
@@ -81,6 +96,7 @@ pi install /path/to/pi-subscription-usage
|
|
|
81
96
|
|
|
82
97
|
- 底部状态栏会自动显示当前额度窗口,在每轮对话结束后及每 5 分钟刷新一次(带 5 分钟缓存)。
|
|
83
98
|
- 执行 `/usage` 会跳过缓存直接拉取最新数据,显示进度条、重置时间(`MM/DD HH:mm`)及账号信息。
|
|
99
|
+
- Claude 例外:不会主动查询额度,只读取 Claude Code 回复中附带的数据(见 [Claude (Claude Code)](#claude-claude-code))。
|
|
84
100
|
|
|
85
101
|
### 使用重置券(OpenAI 与 Codex)
|
|
86
102
|
|
|
@@ -110,7 +126,7 @@ OpenAI 或 Codex 账号里有可用的限额重置券时,`/usage` 会提供使
|
|
|
110
126
|
|
|
111
127
|
## 隐私与安全
|
|
112
128
|
|
|
113
|
-
- 仅从 Pi 自身的登录注册表读取凭据,不读取浏览器 Cookie 或其他工具的凭据文件(例如 Grok 不会读取 `~/.grok/auth.json
|
|
129
|
+
- 仅从 Pi 自身的登录注册表读取凭据,不读取浏览器 Cookie 或其他工具的凭据文件(例如 Grok 不会读取 `~/.grok/auth.json`;Claude 用量来自 bridge 返回的数据,不读取 Claude Code 存在钥匙串里的凭据)。
|
|
114
130
|
- 仅向各提供商的官方接口发起请求,拒绝自定义代理和自定义 Base URL。
|
|
115
131
|
- 令牌不会写入缓存、会话文件、状态栏或报错信息。
|
|
116
132
|
- 不修改任何模型请求。
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@specode/pi-subscription-usage",
|
|
3
|
-
"version": "
|
|
4
|
-
"description": "Show subscription quota for OpenAI, Codex, OpenCode Go, Grok, Kimi, and
|
|
3
|
+
"version": "2.0.0",
|
|
4
|
+
"description": "Show subscription quota for OpenAI, Codex, OpenCode Go, Grok, Kimi, and Claude (via pi-claude-bridge), plus OpenAI and Codex account reset credits in Pi",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
7
7
|
"author": "Specode",
|
|
@@ -23,7 +23,7 @@
|
|
|
23
23
|
"opencode",
|
|
24
24
|
"grok",
|
|
25
25
|
"kimi",
|
|
26
|
-
"
|
|
26
|
+
"claude"
|
|
27
27
|
],
|
|
28
28
|
"files": [
|
|
29
29
|
"index.ts",
|
package/src/format.ts
CHANGED
|
@@ -79,6 +79,7 @@ export function formatProviderState(
|
|
|
79
79
|
let status = "Query Failed";
|
|
80
80
|
if (state.status === "auth-unavailable") status = "Auth Unavailable";
|
|
81
81
|
else if (state.status === "unsupported") status = "Unsupported";
|
|
82
|
+
else if (state.status === "pending") status = "Waiting";
|
|
82
83
|
return `${state.providerName}\n ${status}: ${state.message}`;
|
|
83
84
|
}
|
|
84
85
|
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
// pi-claude-bridge has no usage endpoint Pi can call: Claude Code reports plan
|
|
2
|
+
// usage as rate_limit_event messages, which the bridge replays to Pi as
|
|
3
|
+
// `anthropic-ratelimit-unified-*` headers on after_provider_response.
|
|
4
|
+
// This module turns those headers into a report; nothing here sends a request.
|
|
5
|
+
import type { UsageBucket, UsageReport } from "../types.ts";
|
|
6
|
+
|
|
7
|
+
export const CLAUDE_BRIDGE_PROVIDER_ID = "claude-bridge";
|
|
8
|
+
|
|
9
|
+
const HEADER_PREFIX = "anthropic-ratelimit-unified-";
|
|
10
|
+
// Observed: utilization is a 0..1 fraction. Anything far above 1 means the
|
|
11
|
+
// scale changed, and a guessed percentage would be worse than none.
|
|
12
|
+
const MAX_UTILIZATION = 1.5;
|
|
13
|
+
// Unix seconds; a millisecond value would land past this bound.
|
|
14
|
+
const MAX_EPOCH_SECONDS = 10_000_000_000;
|
|
15
|
+
|
|
16
|
+
const CLAUDE_WINDOWS: readonly {
|
|
17
|
+
abbreviation: string;
|
|
18
|
+
id: string;
|
|
19
|
+
label: string;
|
|
20
|
+
windowMinutes: number;
|
|
21
|
+
}[] = [
|
|
22
|
+
{ abbreviation: "5h", id: "five-hour", label: "5h window", windowMinutes: 300 },
|
|
23
|
+
{ abbreviation: "7d", id: "seven-day", label: "Weekly window", windowMinutes: 10_080 },
|
|
24
|
+
];
|
|
25
|
+
|
|
26
|
+
/** Undefined when the headers carry no usable window, so a non-Claude response leaves the last observation alone. */
|
|
27
|
+
export function normalizeClaudeRateLimitHeaders(
|
|
28
|
+
headers: Record<string, string | undefined>,
|
|
29
|
+
capturedAt: number,
|
|
30
|
+
): UsageReport | undefined {
|
|
31
|
+
const lookup = new Map(
|
|
32
|
+
Object.entries(headers).map(([name, value]) => [name.toLowerCase(), value]),
|
|
33
|
+
);
|
|
34
|
+
// The event names no provider, and a model switch mid-stream can deliver a
|
|
35
|
+
// real Anthropic response under claude-bridge with the same header names.
|
|
36
|
+
// Only the bridge's synthetic response consists of nothing but these.
|
|
37
|
+
if ([...lookup.keys()].some((name) => !name.startsWith(HEADER_PREFIX))) {
|
|
38
|
+
return undefined;
|
|
39
|
+
}
|
|
40
|
+
const buckets: UsageBucket[] = [];
|
|
41
|
+
for (const window of CLAUDE_WINDOWS) {
|
|
42
|
+
const utilization = parseNumber(
|
|
43
|
+
lookup.get(`${HEADER_PREFIX}${window.abbreviation}-utilization`),
|
|
44
|
+
);
|
|
45
|
+
if (
|
|
46
|
+
utilization === undefined ||
|
|
47
|
+
utilization < 0 ||
|
|
48
|
+
utilization > MAX_UTILIZATION
|
|
49
|
+
) {
|
|
50
|
+
continue;
|
|
51
|
+
}
|
|
52
|
+
const used = utilization * 100;
|
|
53
|
+
const resetsAt = parseNumber(
|
|
54
|
+
lookup.get(`${HEADER_PREFIX}${window.abbreviation}-reset`),
|
|
55
|
+
);
|
|
56
|
+
buckets.push({
|
|
57
|
+
id: window.id,
|
|
58
|
+
label: window.label,
|
|
59
|
+
used,
|
|
60
|
+
remaining: Math.max(0, 100 - used),
|
|
61
|
+
unit: "percent",
|
|
62
|
+
windowMinutes: window.windowMinutes,
|
|
63
|
+
...(resetsAt !== undefined && resetsAt > 0 && resetsAt < MAX_EPOCH_SECONDS
|
|
64
|
+
? { resetsAt: Math.floor(resetsAt) }
|
|
65
|
+
: {}),
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
if (buckets.length === 0) return undefined;
|
|
69
|
+
return {
|
|
70
|
+
providerId: CLAUDE_BRIDGE_PROVIDER_ID,
|
|
71
|
+
providerName: "Claude (Claude Code)",
|
|
72
|
+
capturedAt,
|
|
73
|
+
source: "claude-code-rate-limit-event",
|
|
74
|
+
semantics: {
|
|
75
|
+
kind: "consumer-subscription",
|
|
76
|
+
label: "Claude subscription limits",
|
|
77
|
+
},
|
|
78
|
+
buckets,
|
|
79
|
+
metrics: [],
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Claude Code only reports usage after a request, so an observation outlives
|
|
85
|
+
* its windows. A window whose reset has passed starts empty; showing the old
|
|
86
|
+
* percentage would overstate usage until the next response.
|
|
87
|
+
*/
|
|
88
|
+
export function settleClaudeReport(
|
|
89
|
+
report: UsageReport,
|
|
90
|
+
nowMs: number,
|
|
91
|
+
): UsageReport {
|
|
92
|
+
const nowSeconds = nowMs / 1_000;
|
|
93
|
+
return {
|
|
94
|
+
...report,
|
|
95
|
+
buckets: report.buckets.map((bucket) => {
|
|
96
|
+
if (bucket.resetsAt === undefined || bucket.resetsAt > nowSeconds) {
|
|
97
|
+
return bucket;
|
|
98
|
+
}
|
|
99
|
+
const { resetsAt: _expired, ...rest } = bucket;
|
|
100
|
+
return { ...rest, used: 0, remaining: 100 };
|
|
101
|
+
}),
|
|
102
|
+
notes: [`Observed after the last Claude response at ${formatClock(report.capturedAt)}; Claude Code reports usage only with its responses.`],
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function parseNumber(value: string | undefined): number | undefined {
|
|
107
|
+
if (value === undefined || !value.trim()) return undefined;
|
|
108
|
+
const parsed = Number(value);
|
|
109
|
+
return Number.isFinite(parsed) ? parsed : undefined;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function formatClock(epochMs: number): string {
|
|
113
|
+
const date = new Date(epochMs);
|
|
114
|
+
if (Number.isNaN(date.getTime())) return "an unknown time";
|
|
115
|
+
const hour = date.getHours().toString().padStart(2, "0");
|
|
116
|
+
const minute = date.getMinutes().toString().padStart(2, "0");
|
|
117
|
+
return `${hour}:${minute}`;
|
|
118
|
+
}
|
package/src/query.ts
CHANGED
|
@@ -9,18 +9,6 @@ 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";
|
|
24
12
|
import {
|
|
25
13
|
codexAccountIdFromAccessToken,
|
|
26
14
|
normalizeCodexResetCreditsPayload,
|
|
@@ -218,112 +206,8 @@ export const SUPPORTED_ADAPTERS: readonly UsageProviderAdapter[] = [
|
|
|
218
206
|
return normalizeGrokBilling(credits, capturedAt, monthly);
|
|
219
207
|
},
|
|
220
208
|
},
|
|
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
|
-
},
|
|
270
209
|
];
|
|
271
210
|
|
|
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
|
-
|
|
327
211
|
export function adapterForProvider(
|
|
328
212
|
providerId: string | undefined,
|
|
329
213
|
): UsageProviderAdapter | undefined {
|
|
@@ -381,28 +265,13 @@ export async function resolveUsageAuth(
|
|
|
381
265
|
`${adapter.displayName} usage cannot send a proxy-resolved credential to an official usage endpoint.`,
|
|
382
266
|
);
|
|
383
267
|
}
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
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
|
-
|
|
268
|
+
const authorization =
|
|
269
|
+
headerValue(result.auth.headers, "Authorization") ??
|
|
270
|
+
(result.auth.apiKey ? `Bearer ${result.auth.apiKey}` : undefined);
|
|
401
271
|
if (!authorization) return undefined;
|
|
402
272
|
const headers = { Authorization: authorization };
|
|
403
273
|
const secrets = [
|
|
404
274
|
result.auth.apiKey,
|
|
405
|
-
extractedToken && extractedToken !== result.auth.apiKey ? extractedToken : undefined,
|
|
406
275
|
headerValue(result.auth.headers, "Authorization"),
|
|
407
276
|
authorization,
|
|
408
277
|
].filter((value): value is string => Boolean(value));
|
|
@@ -418,7 +287,6 @@ export async function resolveUsageAuth(
|
|
|
418
287
|
actualProviderId: model.provider,
|
|
419
288
|
model,
|
|
420
289
|
openaiClientId: clientId,
|
|
421
|
-
accountEmail,
|
|
422
290
|
// Only the backend credential is sent to ChatGPT. The active API token
|
|
423
291
|
// is used locally for registration matching and cache invalidation.
|
|
424
292
|
headers: companion.headers,
|
|
@@ -428,7 +296,6 @@ export async function resolveUsageAuth(
|
|
|
428
296
|
}
|
|
429
297
|
return {
|
|
430
298
|
actualProviderId: model.provider,
|
|
431
|
-
accountEmail,
|
|
432
299
|
apiKey: result.auth.apiKey,
|
|
433
300
|
headers,
|
|
434
301
|
fingerprint: fingerprintResolvedAuth({ headers }, salt),
|
|
@@ -478,10 +345,7 @@ export async function queryProviderUsage(
|
|
|
478
345
|
return await adapter.query(auth, signal, timeoutMs);
|
|
479
346
|
} catch (error) {
|
|
480
347
|
if (error instanceof Error && error.name === "AbortError") throw error;
|
|
481
|
-
|
|
482
|
-
throw error instanceof UsageUnsupportedError
|
|
483
|
-
? new UsageUnsupportedError(message)
|
|
484
|
-
: new Error(message);
|
|
348
|
+
throw new Error(redactUsageError(errorMessage(error), auth.secrets));
|
|
485
349
|
}
|
|
486
350
|
}
|
|
487
351
|
|
|
@@ -528,11 +392,8 @@ export async function fetchProviderJson(
|
|
|
528
392
|
description,
|
|
529
393
|
);
|
|
530
394
|
if (!response.ok) {
|
|
531
|
-
throw
|
|
532
|
-
|
|
533
|
-
`${description} returned ${response.status} ${response.statusText}: ${redactUsageError(text, auth.secrets)}`,
|
|
534
|
-
),
|
|
535
|
-
{ status: response.status },
|
|
395
|
+
throw new Error(
|
|
396
|
+
`${description} returned ${response.status} ${response.statusText}: ${redactUsageError(text, auth.secrets)}`,
|
|
536
397
|
);
|
|
537
398
|
}
|
|
538
399
|
let parsed: unknown;
|
package/src/types.ts
CHANGED
|
@@ -53,7 +53,6 @@ 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;
|
|
57
56
|
apiKey?: string;
|
|
58
57
|
headers: Record<string, string>;
|
|
59
58
|
fingerprint: string;
|
|
@@ -85,6 +84,7 @@ export type ProviderUsageState =
|
|
|
85
84
|
| {
|
|
86
85
|
providerId: string;
|
|
87
86
|
providerName: string;
|
|
88
|
-
|
|
87
|
+
/** `pending`: an observed provider has not reported usage yet. */
|
|
88
|
+
status: "unsupported" | "auth-unavailable" | "query-failed" | "pending";
|
|
89
89
|
message: string;
|
|
90
90
|
};
|
package/src/usage.ts
CHANGED
|
@@ -30,6 +30,11 @@ import {
|
|
|
30
30
|
resolveCodexResetAuth,
|
|
31
31
|
} from "./codex-resets.ts";
|
|
32
32
|
import { formatProviderState } from "./format.ts";
|
|
33
|
+
import {
|
|
34
|
+
CLAUDE_BRIDGE_PROVIDER_ID,
|
|
35
|
+
normalizeClaudeRateLimitHeaders,
|
|
36
|
+
settleClaudeReport,
|
|
37
|
+
} from "./providers/claude-bridge.ts";
|
|
33
38
|
import { CODEX_PROVIDER_ID } from "./providers/codex-constants.ts";
|
|
34
39
|
import { OPENAI_PROVIDER_ID } from "./providers/openai.ts";
|
|
35
40
|
import {
|
|
@@ -50,6 +55,7 @@ import type {
|
|
|
50
55
|
ResolvedUsageAuth,
|
|
51
56
|
UsageModel,
|
|
52
57
|
UsageProviderAdapter,
|
|
58
|
+
UsageReport,
|
|
53
59
|
} from "./types.ts";
|
|
54
60
|
|
|
55
61
|
const CACHE_TTL_MS = 5 * 60 * 1_000;
|
|
@@ -69,16 +75,15 @@ type StableCurrent = {
|
|
|
69
75
|
|
|
70
76
|
export default function subscriptionUsage(pi: ExtensionAPI): void {
|
|
71
77
|
const cache = new UsageCache(CACHE_TTL_MS);
|
|
72
|
-
const failureBackoff = new Map<
|
|
73
|
-
string,
|
|
74
|
-
{ until: number; message: string; status: "unsupported" | "query-failed" }
|
|
75
|
-
>();
|
|
78
|
+
const failureBackoff = new Map<string, { until: number; message: string }>();
|
|
76
79
|
const activeControllers = new Set<AbortController>();
|
|
77
80
|
let sessionActive = false;
|
|
78
81
|
let displayMode: UsageDisplayMode = DEFAULT_USAGE_DISPLAY_MODE;
|
|
79
82
|
let statusGeneration = 0;
|
|
80
83
|
let statusController: AbortController | undefined;
|
|
81
84
|
let statusTimer: ReturnType<typeof setTimeout> | undefined;
|
|
85
|
+
// Holds no credential, so session_shutdown leaves it; nothing reads it after.
|
|
86
|
+
let claudeObservation: UsageReport | undefined;
|
|
82
87
|
|
|
83
88
|
function emitUsageStatus(event: UsageStatusEvent): void {
|
|
84
89
|
pi.events.emit(USAGE_STATUS_EVENT, event);
|
|
@@ -135,7 +140,10 @@ export default function subscriptionUsage(pi: ExtensionAPI): void {
|
|
|
135
140
|
model: UsageModel,
|
|
136
141
|
schedule: boolean,
|
|
137
142
|
): void {
|
|
138
|
-
if (
|
|
143
|
+
if (
|
|
144
|
+
outcome.state.status === "unsupported" ||
|
|
145
|
+
outcome.state.status === "pending"
|
|
146
|
+
) {
|
|
139
147
|
clearStatusTimer();
|
|
140
148
|
safeSetStatus(ctx, undefined);
|
|
141
149
|
emitUnavailableUsage();
|
|
@@ -227,7 +235,7 @@ export default function subscriptionUsage(pi: ExtensionAPI): void {
|
|
|
227
235
|
state: {
|
|
228
236
|
providerId: adapter.id,
|
|
229
237
|
providerName: adapter.displayName,
|
|
230
|
-
status:
|
|
238
|
+
status: "query-failed",
|
|
231
239
|
message: failure.message,
|
|
232
240
|
},
|
|
233
241
|
fingerprint: auth.fingerprint,
|
|
@@ -254,19 +262,15 @@ export default function subscriptionUsage(pi: ExtensionAPI): void {
|
|
|
254
262
|
} catch (error) {
|
|
255
263
|
if (isAbortError(error) || !sessionActive) throw error;
|
|
256
264
|
const message = errorMessage(error);
|
|
257
|
-
const status = error instanceof UsageUnsupportedError
|
|
258
|
-
? "unsupported"
|
|
259
|
-
: "query-failed";
|
|
260
265
|
failureBackoff.set(failureKey, {
|
|
261
266
|
until: Date.now() + FAILURE_BACKOFF_MS,
|
|
262
267
|
message,
|
|
263
|
-
status,
|
|
264
268
|
});
|
|
265
269
|
return {
|
|
266
270
|
state: {
|
|
267
271
|
providerId: adapter.id,
|
|
268
272
|
providerName: adapter.displayName,
|
|
269
|
-
status,
|
|
273
|
+
status: "query-failed",
|
|
270
274
|
message,
|
|
271
275
|
},
|
|
272
276
|
fingerprint: auth.fingerprint,
|
|
@@ -280,6 +284,7 @@ export default function subscriptionUsage(pi: ExtensionAPI): void {
|
|
|
280
284
|
force: boolean,
|
|
281
285
|
signal: AbortSignal,
|
|
282
286
|
): Promise<QueryOutcome> {
|
|
287
|
+
if (isObservedProvider(model)) return observedClaudeOutcome();
|
|
283
288
|
const adapter = adapterForProvider(model?.provider);
|
|
284
289
|
if (!adapter) {
|
|
285
290
|
return {
|
|
@@ -296,6 +301,29 @@ export default function subscriptionUsage(pi: ExtensionAPI): void {
|
|
|
296
301
|
return queryAdapterState(ctx, adapter, force, signal);
|
|
297
302
|
}
|
|
298
303
|
|
|
304
|
+
/** Claude has no query to force; /usage and refreshes reread the last observation. */
|
|
305
|
+
function observedClaudeOutcome(): QueryOutcome {
|
|
306
|
+
const providerName = "Claude (Claude Code)";
|
|
307
|
+
if (!claudeObservation) {
|
|
308
|
+
return {
|
|
309
|
+
state: {
|
|
310
|
+
providerId: CLAUDE_BRIDGE_PROVIDER_ID,
|
|
311
|
+
providerName,
|
|
312
|
+
status: "pending",
|
|
313
|
+
message: "Claude Code has not reported usage in this session yet. It reports usage with its responses, which requires pi-claude-bridge 0.9.3 or later.",
|
|
314
|
+
},
|
|
315
|
+
};
|
|
316
|
+
}
|
|
317
|
+
return {
|
|
318
|
+
state: {
|
|
319
|
+
providerId: CLAUDE_BRIDGE_PROVIDER_ID,
|
|
320
|
+
providerName,
|
|
321
|
+
status: "ready",
|
|
322
|
+
report: settleClaudeReport(claudeObservation, Date.now()),
|
|
323
|
+
},
|
|
324
|
+
};
|
|
325
|
+
}
|
|
326
|
+
|
|
299
327
|
async function outcomeStillCurrent(
|
|
300
328
|
ctx: ExtensionContext,
|
|
301
329
|
model: UsageModel | undefined,
|
|
@@ -344,7 +372,8 @@ export default function subscriptionUsage(pi: ExtensionAPI): void {
|
|
|
344
372
|
model: UsageModel | undefined,
|
|
345
373
|
force: boolean,
|
|
346
374
|
): Promise<void> {
|
|
347
|
-
|
|
375
|
+
const observed = isObservedProvider(model);
|
|
376
|
+
if ((!observed && !adapterForProvider(model?.provider)) || !model) {
|
|
348
377
|
clearStatus(ctx);
|
|
349
378
|
return;
|
|
350
379
|
}
|
|
@@ -360,7 +389,8 @@ export default function subscriptionUsage(pi: ExtensionAPI): void {
|
|
|
360
389
|
!controller.signal.aborted &&
|
|
361
390
|
modelIdentity(ctx.model) === modelIdentity(model);
|
|
362
391
|
try {
|
|
363
|
-
|
|
392
|
+
// An observed provider answers immediately; a placeholder would only flicker.
|
|
393
|
+
if (!observed) safeSetStatus(ctx, "usage …");
|
|
364
394
|
const outcome = await queryCurrentState(
|
|
365
395
|
ctx,
|
|
366
396
|
model,
|
|
@@ -623,6 +653,13 @@ export default function subscriptionUsage(pi: ExtensionAPI): void {
|
|
|
623
653
|
pi.on("agent_settled", (_event, ctx) => {
|
|
624
654
|
if (ctx.hasUI) startStatusRefresh(ctx, ctx.model, false);
|
|
625
655
|
});
|
|
656
|
+
pi.on("after_provider_response", (event, ctx) => {
|
|
657
|
+
if (!isObservedProvider(ctx.model)) return;
|
|
658
|
+
const report = normalizeClaudeRateLimitHeaders(event.headers, Date.now());
|
|
659
|
+
if (!report) return;
|
|
660
|
+
claudeObservation = report;
|
|
661
|
+
if (ctx.hasUI && sessionActive) startStatusRefresh(ctx, ctx.model, false);
|
|
662
|
+
});
|
|
626
663
|
pi.on("session_shutdown", (_event, ctx) => {
|
|
627
664
|
sessionActive = false;
|
|
628
665
|
statusGeneration += 1;
|
|
@@ -636,3 +673,7 @@ export default function subscriptionUsage(pi: ExtensionAPI): void {
|
|
|
636
673
|
emitUnavailableUsage();
|
|
637
674
|
});
|
|
638
675
|
}
|
|
676
|
+
|
|
677
|
+
function isObservedProvider(model: UsageModel | undefined): boolean {
|
|
678
|
+
return model?.provider === CLAUDE_BRIDGE_PROVIDER_ID;
|
|
679
|
+
}
|
|
@@ -1,372 +0,0 @@
|
|
|
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
|
-
}
|