@specode/pi-subscription-usage 1.1.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -6,6 +6,8 @@ A Pi extension that shows the active account's subscription quota in one consist
6
6
 
7
7
  Supported providers:
8
8
 
9
+ - **OpenAI (ChatGPT subscription)** — app-specific subscription windows for Pi's `openai` OAuth login, rendered with the same quota bars and footer. Also requires `openai-codex` OAuth in Pi for the same ChatGPT account/workspace: its backend credential reads `/wham/usage/chatpass/apps`, and the active OpenAI token's application ID must match exactly one returned registration. Only that application's windows are shown, never Codex's quota. Both credentials participate in cache invalidation. No browser cookies are used, and no reset action is offered for this provider.
10
+
9
11
  - **OpenAI Codex** — 5-hour and weekly quota, model-specific quota, and confirmed reset-credit redemption.
10
12
  - **OpenCode Go** — 5-hour, weekly, and monthly windows.
11
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.
@@ -88,7 +90,7 @@ The extension publishes two status layers:
88
90
  - 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.
89
91
  - Structured window data through the `subscription-usage/status/v1` event.
90
92
 
91
- Windows are always ordered as `5h / 1w / 1m / other`. Other extensions can consume the structured event to provide their own icons, colors, and layout without parsing display text. Ready events include `displayMode`; each window includes `displayPercent`, `remainingPercent`, and `usedPercent`. Consumers should render `displayPercent` while using the explicit remaining/used fields for semantic decisions such as colors or alerts.
93
+ Windows are always ordered as `5h / 1w / 1m / other`. Other extensions can consume the structured event to provide their own icons, colors, and layout without parsing display text. Ready events include `displayMode`; each window includes `displayPercent`, `remainingPercent`, and `usedPercent`. Consumers should render `displayPercent` while using the explicit remaining/used fields for semantic decisions such as colors or alerts. When the provider reports a future reset time, a window also carries `resetCountdown` (for example `2h13m`), computed at publish time with the same format and refresh cadence as the footer text; consumers can show it as-is instead of formatting `resetsAt` themselves.
92
94
 
93
95
  ## Security boundaries
94
96
 
@@ -127,6 +129,8 @@ pi --no-extensions --offline -e ./index.ts --list-models
127
129
 
128
130
  ## Stability
129
131
 
132
+ OpenAI app usage also depends on an undocumented ChatGPT endpoint. If the companion Codex login is missing, sign in to **OpenAI Codex** through `/login` without changing the active OpenAI model. An account/workspace mismatch, missing registration, or missing windows produces an error rather than displaying another account's quota. `Plan Allowance` is the configured share the app may use, not its remaining percentage. `Source` identifies this as the matching app in Pi's Codex account; matching application IDs is not independent cryptographic verification of both token identities.
133
+
130
134
  Codex reset, Grok billing, and Kimi usage rely on undocumented provider APIs that may change. When an API fails, the extension reports the query error and does not fall back to uncontrolled credential or proxy paths.
131
135
 
132
136
  ## License
package/README.zh-CN.md CHANGED
@@ -6,6 +6,8 @@
6
6
 
7
7
  支持以下提供商:
8
8
 
9
+ - **OpenAI(ChatGPT 订阅)**:读取 Pi `openai` OAuth 登录对应应用的订阅窗口,沿用原有进度条和底部样式。同时需要在 Pi 登录同一 ChatGPT 账户/工作区的 `openai-codex`:用其后端凭据读取 `/wham/usage/chatpass/apps`,并将当前 OpenAI Token 的应用 ID 与返回的注册应用精确匹配。只展示匹配应用的额度,不使用 Codex 自身额度;任一凭据变化都会使缓存失效。不读取浏览器 Cookie,也不提供此模式下的重置操作。
10
+
9
11
  - **OpenAI Codex**:5 小时与每周额度、模型专属额度,以及需要确认的重置次数兑换。
10
12
  - **OpenCode Go**:5 小时、每周和每月窗口。
11
13
  - **Grok**:每周和/或每月额度;只使用 Pi 的 `xai` / `xai-auth` OAuth 凭据,并先验证账户身份。若 weekly `currentPeriod` 存在但省略了 `creditUsagePercent`,按已用 0% 处理(proto3 在周期重置后会省略 0)。统一账单账户仍会探测默认月度接口,但 weekly 窗口已经可展示时,月度探测失败不再让整次查询失败。窗口与其他提供商一样使用 `5h / 1w / 1m` 状态格式。
@@ -88,7 +90,7 @@ Codex 结果会按以下额度域分组:
88
90
  - 不含提供商名称或图标的普通 `setStatus` 文本,例如 `5h 99% ↻2h13m · 1w 85% ↻3d4h · 1m 60%`。`↻` 后是距离该窗口重置的倒计时,仅在提供商返回未来的重置时间时显示。底部状态每 5 分钟及每轮 agent 结束后刷新,因此倒计时最多可能滞后约 5 分钟。
89
91
  - 通过 `subscription-usage/status/v1` 事件发布的结构化窗口数据。
90
92
 
91
- 窗口始终按 `5h / 1w / 1m / other` 排序。其他扩展可以直接消费结构化事件,自定义图标、颜色和布局,而不必解析显示文本。就绪事件包含 `displayMode`,每个窗口包含 `displayPercent`、`remainingPercent` 和 `usedPercent`;消费者应展示 `displayPercent`,并在颜色或告警等语义判断中使用明确的剩余/已用字段。
93
+ 窗口始终按 `5h / 1w / 1m / other` 排序。其他扩展可以直接消费结构化事件,自定义图标、颜色和布局,而不必解析显示文本。就绪事件包含 `displayMode`,每个窗口包含 `displayPercent`、`remainingPercent` 和 `usedPercent`;消费者应展示 `displayPercent`,并在颜色或告警等语义判断中使用明确的剩余/已用字段。提供商返回未来的重置时间时,窗口还包含 `resetCountdown`(例如 `2h13m`),在发布事件时计算,格式和刷新频率与底部状态文本一致;消费者可直接展示,无需自行根据 `resetsAt` 格式化。
92
94
 
93
95
  ## 安全边界
94
96
 
@@ -127,6 +129,8 @@ pi --no-extensions --offline -e ./index.ts --list-models
127
129
 
128
130
  ## 稳定性
129
131
 
132
+ OpenAI 应用额度也依赖未公开的 ChatGPT 接口。缺少配套 Codex 登录时,通过 `/login` 登录 **OpenAI Codex**,无需切换当前 OpenAI 模型。账户/工作区不匹配、找不到应用注册或额度窗口时会报告错误,不展示其他账户的额度。`Plan Allowance` 表示允许应用使用的套餐份额,不是剩余额度百分比。`Source` 明确标注这是 Pi Codex 登录账户内匹配应用的数据;应用 ID 匹配不是对两套令牌身份的独立验签证明。
133
+
130
134
  Codex 重置、Grok 账单和 Kimi 额度依赖未公开的提供商 API,这些 API 可能发生变化。如果 API 调用失败,本扩展只会报告查询错误,不会退回到不受控制的凭据或代理路径。
131
135
 
132
136
  ## 许可证
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@specode/pi-subscription-usage",
3
- "version": "1.1.0",
4
- "description": "Show subscription quota and Codex reset credits for Codex, OpenCode Go, Grok, and Kimi in Pi",
3
+ "version": "1.2.0",
4
+ "description": "Show subscription quota for OpenAI, Codex, OpenCode Go, Grok, and Kimi, plus Codex reset credits in Pi",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "author": "Specode",
@@ -0,0 +1,98 @@
1
+ import { sanitizeDisplayText } from "../core.ts";
2
+ import type { UsageBucket, UsageReport } from "../types.ts";
3
+
4
+ export const OPENAI_PROVIDER_ID = "openai";
5
+
6
+ /** Decode only routing metadata from Pi's active OAuth credential, not identity claims. */
7
+ export function openaiClientIdFromAuthorization(authorization: string): string {
8
+ try {
9
+ const token = /^Bearer\s+(\S+)$/iu.exec(authorization)?.[1];
10
+ const parts = token?.split(".");
11
+ if (parts?.length !== 3) throw new Error();
12
+ const claims = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8"));
13
+ if (
14
+ claims.iss !== "https://auth.openai.com" ||
15
+ claims.aud !== "https://api.openai.com/v1" ||
16
+ typeof claims.scope !== "string" ||
17
+ !claims.scope.split(/\s+/u).includes("chatgpt.tokens.use.direct") ||
18
+ typeof claims.client_id !== "string" ||
19
+ !/^oaiapp_[a-zA-Z0-9_-]+$/u.test(claims.client_id)
20
+ ) throw new Error();
21
+ return claims.client_id;
22
+ } catch {
23
+ throw new Error("OpenAI usage requires a Sign in with ChatGPT OAuth credential with an application ID.");
24
+ }
25
+ }
26
+
27
+ /**
28
+ * The ChatGPT usage page reads app-scoped subscription windows here, separately
29
+ * from Codex's rate_limit. Match the active registration, never an app name or
30
+ * the first result: a different Codex account must not supply another quota.
31
+ */
32
+ export function normalizeOpenAIUsage(
33
+ payload: unknown,
34
+ clientId: string,
35
+ capturedAt: number,
36
+ ): UsageReport {
37
+ const root = asObject(payload);
38
+ const matches = Array.isArray(root?.items)
39
+ ? root.items.map(asObject).filter((item) => item?.id === clientId)
40
+ : [];
41
+ if (!clientId || matches.length !== 1) {
42
+ throw new Error("The active OpenAI application was not uniquely found in this Codex account. Sign in to OpenAI and OpenAI Codex with the same ChatGPT account/workspace.");
43
+ }
44
+ const app = matches[0]!;
45
+ const windows = Array.isArray(app.windows) ? app.windows : [];
46
+ const buckets: UsageBucket[] = windows.map((raw, index) => {
47
+ const window = asObject(raw);
48
+ const used = number(window?.used_percent);
49
+ const remaining = number(window?.remaining_percent);
50
+ const seconds = number(window?.limit_window_seconds);
51
+ const reset = number(window?.reset_at);
52
+ if (
53
+ used === undefined || used < 0 || used > 100 ||
54
+ seconds === undefined || seconds <= 0 ||
55
+ (remaining !== undefined && (remaining < 0 || remaining > 100))
56
+ ) throw new Error("OpenAI subscription returned an invalid usage window.");
57
+ return {
58
+ id: `chatpass:${index}`,
59
+ label: "App subscription limit",
60
+ used,
61
+ remaining: remaining ?? 100 - used,
62
+ limit: 100,
63
+ unit: "percent",
64
+ windowMinutes: Math.ceil(seconds / 60),
65
+ ...(reset !== undefined && reset > 0 ? { resetsAt: reset } : {}),
66
+ };
67
+ });
68
+ if (buckets.length === 0) {
69
+ throw new Error("OpenAI subscription returned no displayable app usage windows.");
70
+ }
71
+ const name = typeof app.name === "string" ? sanitizeDisplayText(app.name, 80) : "";
72
+ const allowance = number(app.allowed_usage_percent);
73
+ return {
74
+ providerId: OPENAI_PROVIDER_ID,
75
+ providerName: "OpenAI (ChatGPT subscription)",
76
+ capturedAt,
77
+ source: "openai-chatpass-pi-auth",
78
+ semantics: { kind: "consumer-subscription", label: "ChatGPT app subscription limits" },
79
+ buckets,
80
+ metrics: [
81
+ { id: "source", label: "Source", value: "Matched app in Pi Codex account" },
82
+ ...(name ? [{ id: "app", label: "App", value: name }] : []),
83
+ ...(allowance !== undefined && allowance >= 0 && allowance <= 100
84
+ ? [{ id: "allowance", label: "Plan Allowance", value: `${allowance}%` }]
85
+ : []),
86
+ ],
87
+ };
88
+ }
89
+
90
+ function asObject(value: unknown): Record<string, unknown> | undefined {
91
+ return value && typeof value === "object" && !Array.isArray(value)
92
+ ? value as Record<string, unknown>
93
+ : undefined;
94
+ }
95
+
96
+ function number(value: unknown): number | undefined {
97
+ return typeof value === "number" && Number.isFinite(value) ? value : undefined;
98
+ }
package/src/query.ts CHANGED
@@ -21,6 +21,11 @@ import {
21
21
  shouldProbeGrokMonthly,
22
22
  } from "./providers/grok.ts";
23
23
  import { normalizeKimiUsage } from "./providers/kimi.ts";
24
+ import {
25
+ OPENAI_PROVIDER_ID,
26
+ normalizeOpenAIUsage,
27
+ openaiClientIdFromAuthorization,
28
+ } from "./providers/openai.ts";
24
29
  import { normalizeOpenCodeGoUsage } from "./providers/opencode-go.ts";
25
30
  import type {
26
31
  ResolvedUsageAuth,
@@ -48,6 +53,28 @@ type PiModel = NonNullable<ExtensionContext["model"]>;
48
53
  export const AUTH_FINGERPRINT_SALT = randomBytes(32);
49
54
 
50
55
  export const SUPPORTED_ADAPTERS: readonly UsageProviderAdapter[] = [
56
+ {
57
+ id: OPENAI_PROVIDER_ID,
58
+ displayName: "OpenAI (ChatGPT subscription)",
59
+ providerIds: [OPENAI_PROVIDER_ID],
60
+ officialOrigins: ["https://api.openai.com"],
61
+ requiresOAuth: true,
62
+ semantics: { kind: "consumer-subscription", label: "ChatGPT app subscription limits" },
63
+ async query(auth, signal, timeoutMs) {
64
+ if (!auth.openaiClientId) throw new Error("OpenAI application identity is unavailable.");
65
+ return normalizeOpenAIUsage(
66
+ await fetchProviderJson(
67
+ `${CODEX_USAGE_URL}/chatpass/apps`,
68
+ auth,
69
+ signal,
70
+ timeoutMs,
71
+ "OpenAI app usage endpoint",
72
+ ),
73
+ auth.openaiClientId,
74
+ Date.now(),
75
+ );
76
+ },
77
+ },
51
78
  {
52
79
  id: CODEX_PROVIDER_ID,
53
80
  displayName: "OpenAI Codex",
@@ -169,18 +196,26 @@ export function adapterForProvider(
169
196
  );
170
197
  }
171
198
 
199
+ /** A configured provider mode that does not offer subscription usage. */
200
+ export class UsageUnsupportedError extends Error {
201
+ name = "UsageUnsupportedError";
202
+ }
203
+
172
204
  export async function resolveUsageAuth(
173
205
  ctx: ExtensionContext,
174
206
  adapter: UsageProviderAdapter,
175
207
  salt: Uint8Array = AUTH_FINGERPRINT_SALT,
176
208
  ): Promise<ResolvedUsageAuth | undefined> {
177
209
  const current = ctx.model;
210
+ const UnsupportedModeError = adapter.id === OPENAI_PROVIDER_ID
211
+ ? UsageUnsupportedError
212
+ : Error;
178
213
  if (
179
214
  current &&
180
215
  adapter.providerIds.includes(current.provider) &&
181
216
  !hasOfficialOrigin(current.baseUrl, adapter)
182
217
  ) {
183
- throw new Error(
218
+ throw new UnsupportedModeError(
184
219
  `${adapter.displayName} usage cannot send a custom provider credential to an official usage endpoint.`,
185
220
  );
186
221
  }
@@ -199,14 +234,14 @@ export async function resolveUsageAuth(
199
234
  );
200
235
  if (!model) return undefined;
201
236
  if (adapter.requiresOAuth && !ctx.modelRegistry.isUsingOAuth(model)) {
202
- throw new Error(
237
+ throw new UnsupportedModeError(
203
238
  `${adapter.displayName} usage requires Pi OAuth; API-key auth is not accepted.`,
204
239
  );
205
240
  }
206
241
  const result = await ctx.modelRegistry.getProviderAuth(model.provider);
207
242
  if (!result) return undefined;
208
243
  if (result.auth.baseUrl && !hasOfficialOrigin(result.auth.baseUrl, adapter)) {
209
- throw new Error(
244
+ throw new UnsupportedModeError(
210
245
  `${adapter.displayName} usage cannot send a proxy-resolved credential to an official usage endpoint.`,
211
246
  );
212
247
  }
@@ -220,6 +255,24 @@ export async function resolveUsageAuth(
220
255
  headerValue(result.auth.headers, "Authorization"),
221
256
  authorization,
222
257
  ].filter((value): value is string => Boolean(value));
258
+ if (adapter.id === OPENAI_PROVIDER_ID) {
259
+ const clientId = openaiClientIdFromAuthorization(authorization);
260
+ const codexAdapter = adapterForProvider(CODEX_PROVIDER_ID)!;
261
+ const companion = await resolveUsageAuth(ctx, { ...codexAdapter, requiresOAuth: true }, salt);
262
+ if (!companion) {
263
+ throw new Error("OpenAI app usage also requires OpenAI Codex OAuth in Pi for the same ChatGPT account/workspace. Run /login for OpenAI Codex; keep OpenAI as the active model.");
264
+ }
265
+ return {
266
+ actualProviderId: model.provider,
267
+ model,
268
+ openaiClientId: clientId,
269
+ // Only the backend credential is sent to ChatGPT. The active API token
270
+ // is used locally for registration matching and cache invalidation.
271
+ headers: companion.headers,
272
+ fingerprint: fingerprintResolvedAuth({ apiKey: authorization, headers: companion.headers }, salt),
273
+ secrets: [...secrets, ...companion.secrets, clientId],
274
+ };
275
+ }
223
276
  return {
224
277
  actualProviderId: model.provider,
225
278
  apiKey: result.auth.apiKey,
package/src/status.ts CHANGED
@@ -27,6 +27,8 @@ export interface UsageStatusWindow {
27
27
  displayPercent: number;
28
28
  windowMinutes?: number;
29
29
  resetsAt?: number;
30
+ /** Countdown to `resetsAt` at publish time, such as `2h13m`; absent once the reset has passed. */
31
+ resetCountdown?: string;
30
32
  }
31
33
 
32
34
  export type UsageStatusEvent =
@@ -51,6 +53,7 @@ export function buildUsageStatusEvent(
51
53
  report: UsageReport,
52
54
  model?: UsageModel,
53
55
  displayMode: UsageDisplayMode = DEFAULT_USAGE_DISPLAY_MODE,
56
+ nowMs: number = Date.now(),
54
57
  ): UsageStatusEvent {
55
58
  const buckets = bucketsForModel(report, model);
56
59
  const windows = sortUsageBuckets(buckets).flatMap((bucket) => {
@@ -64,6 +67,10 @@ export function buildUsageStatusEvent(
64
67
  ) {
65
68
  return [];
66
69
  }
70
+ const resetCountdown =
71
+ bucket.resetsAt === undefined
72
+ ? undefined
73
+ : formatResetCountdown(bucket.resetsAt * 1_000 - nowMs);
67
74
  return [
68
75
  {
69
76
  kind: usageWindowKind(bucket),
@@ -75,6 +82,7 @@ export function buildUsageStatusEvent(
75
82
  ? {}
76
83
  : { windowMinutes: bucket.windowMinutes }),
77
84
  ...(bucket.resetsAt === undefined ? {} : { resetsAt: bucket.resetsAt }),
85
+ ...(resetCountdown === undefined ? {} : { resetCountdown }),
78
86
  } satisfies UsageStatusWindow,
79
87
  ];
80
88
  });
@@ -95,16 +103,14 @@ export function formatUsageStatusline(
95
103
  displayMode: UsageDisplayMode = DEFAULT_USAGE_DISPLAY_MODE,
96
104
  nowMs: number = Date.now(),
97
105
  ): string | undefined {
98
- const event = buildUsageStatusEvent(report, model, displayMode);
106
+ const event = buildUsageStatusEvent(report, model, displayMode, nowMs);
99
107
  if (event.status !== "ready" || event.windows.length === 0) return undefined;
100
108
  return event.windows
101
109
  .map((window) => {
102
- const countdown =
103
- window.resetsAt === undefined
104
- ? undefined
105
- : formatResetCountdown(window.resetsAt * 1_000 - nowMs);
106
110
  const percent = `${window.label} ${formatUsagePercent(window.displayPercent)}%`;
107
- return countdown ? `${percent} ↻${countdown}` : percent;
111
+ return window.resetCountdown
112
+ ? `${percent} ↻${window.resetCountdown}`
113
+ : percent;
108
114
  })
109
115
  .join(" · ");
110
116
  }
package/src/types.ts CHANGED
@@ -49,6 +49,8 @@ export interface UsageReport {
49
49
 
50
50
  export interface ResolvedUsageAuth {
51
51
  actualProviderId: string;
52
+ /** Active OpenAI OAuth registration, matched against the ChatGPT app list. */
53
+ openaiClientId?: string;
52
54
  apiKey?: string;
53
55
  headers: Record<string, string>;
54
56
  fingerprint: string;
package/src/usage.ts CHANGED
@@ -43,6 +43,7 @@ import {
43
43
  adapterForProvider,
44
44
  queryProviderUsage,
45
45
  resolveUsageAuth,
46
+ UsageUnsupportedError,
46
47
  } from "./query.ts";
47
48
  import type {
48
49
  ProviderUsageState,
@@ -153,10 +154,16 @@ export default function subscriptionUsage(pi: ExtensionAPI): void {
153
154
  }
154
155
  return;
155
156
  }
157
+ const nowMs = Date.now();
156
158
  emitUsageStatus(
157
- buildUsageStatusEvent(outcome.state.report, model, displayMode),
159
+ buildUsageStatusEvent(outcome.state.report, model, displayMode, nowMs),
160
+ );
161
+ const value = formatUsageStatusline(
162
+ outcome.state.report,
163
+ model,
164
+ displayMode,
165
+ nowMs,
158
166
  );
159
- const value = formatUsageStatusline(outcome.state.report, model, displayMode);
160
167
  if (!safeSetStatus(ctx, value)) return;
161
168
  if (schedule && sessionActive) scheduleStatusRefresh(ctx, model);
162
169
  }
@@ -181,7 +188,9 @@ export default function subscriptionUsage(pi: ExtensionAPI): void {
181
188
  state: {
182
189
  providerId: adapter.id,
183
190
  providerName: adapter.displayName,
184
- status: "auth-unavailable",
191
+ status: error instanceof UsageUnsupportedError
192
+ ? "unsupported"
193
+ : "auth-unavailable",
185
194
  message: errorMessage(error),
186
195
  },
187
196
  };