@specode/pi-subscription-usage 0.2.2 → 0.2.3

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
@@ -9,7 +9,7 @@ Supported providers:
9
9
  - **OpenAI Codex** — 5-hour and weekly quota, model-specific quota, and confirmed reset-credit redemption.
10
10
  - **OpenCode Go** — 5-hour, weekly, and monthly windows.
11
11
  - **Grok** — weekly and/or monthly quota using only Pi's `xai` / `xai-auth` OAuth credentials, with account identity verification. Unified SuperGrok billing is read from the default monthly endpoint when `?format=credits` omits window percents. Windows use the same `5h / 1w / 1m` status format as other providers.
12
- - **Kimi Coding** — 5-hour and weekly windows.
12
+ - **Kimi Coding** — 5-hour and weekly windows, plus the membership plan reported by the usage API.
13
13
 
14
14
  The extension does not implement or modify Codex Fast mode and never rewrites model requests.
15
15
 
@@ -43,7 +43,7 @@ Run:
43
43
  /usage
44
44
  ```
45
45
 
46
- Each invocation bypasses the cache and queries the current provider again. Quota windows use a uniform display with `MM/DD HH:mm` reset times.
46
+ 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.
47
47
 
48
48
  Codex results are grouped by quota domain in this order:
49
49
 
@@ -51,7 +51,7 @@ Codex results are grouped by quota domain in this order:
51
51
  2. Model-specific sections
52
52
  3. `Account`
53
53
 
54
- Windows from different domains are never interleaved. Run `/usage` again whenever you want to refresh; the command does not show refresh, provider-switching, or all-provider menus.
54
+ Windows from different domains are never interleaved. When available, the Codex `Account` section displays the email decoded locally from the active OAuth token. Run `/usage` again whenever you want to refresh; the command does not show refresh, provider-switching, or all-provider menus.
55
55
 
56
56
  The reset menu appears only when Codex reports redeemable reset credits. Grok's current API exposes quota windows and natural reset times, but no verified manual-reset endpoint or reset-credit count, so the extension never invents a reset action. Grok windows still render through the same `/usage` bars and status event as Codex, OpenCode Go, and Kimi.
57
57
 
@@ -96,6 +96,7 @@ Windows are always ordered as `5h / 1w / 1m / other`. Other extensions can consu
96
96
  - Codex reset additionally reads Pi's stored OAuth credential through the public `readStoredCredential()` API, solely to verify that it exactly matches the active runtime account before redemption.
97
97
  - Grok never reads `~/.grok/auth.json` and never accepts an API key in place of subscription OAuth.
98
98
  - Credentials are never written to caches, sessions, the status line, or error messages. Cache keys contain only in-process HMAC fingerprints.
99
+ - The Codex email is decoded locally for the `/usage` account panel and is not included in the footer or structured status event.
99
100
  - Credentials are sent only to the corresponding official domains. Custom proxies and custom base URLs are rejected.
100
101
  - Codex reset is the only write operation. It is shown only when redeemable credits exist and always requires explicit confirmation.
101
102
 
package/README.zh-CN.md CHANGED
@@ -9,7 +9,7 @@
9
9
  - **OpenAI Codex**:5 小时与每周额度、模型专属额度,以及需要确认的重置次数兑换。
10
10
  - **OpenCode Go**:5 小时、每周和每月窗口。
11
11
  - **Grok**:每周和/或每月额度;只使用 Pi 的 `xai` / `xai-auth` OAuth 凭据,并先验证账户身份。统一账单账户在 `?format=credits` 缺少窗口百分比时,会再读取默认的月度账单接口。窗口与其他提供商一样使用 `5h / 1w / 1m` 状态格式。
12
- - **Kimi Coding**:5 小时和每周窗口。
12
+ - **Kimi Coding**:5 小时和每周窗口,以及额度接口返回的会员套餐。
13
13
 
14
14
  本扩展不实现或修改 Codex Fast 模式,也不会改写模型请求。
15
15
 
@@ -43,7 +43,7 @@ Pi package 拥有当前用户的完整系统权限。安装第三方 package 前
43
43
  /usage
44
44
  ```
45
45
 
46
- 每次调用都会跳过缓存并重新查询当前提供商。所有额度窗口都使用统一格式,并以 `MM/DD HH:mm` 显示重置时间。
46
+ 每次调用都会跳过缓存并重新查询当前提供商。所有额度窗口都使用统一格式,并以 `MM/DD HH:mm` 显示重置时间。提供商返回账户指标时,这些指标会统一显示在额度窗口之后的独立 `Account` 区域。
47
47
 
48
48
  Codex 结果会按以下额度域分组:
49
49
 
@@ -51,7 +51,7 @@ Codex 结果会按以下额度域分组:
51
51
  2. 各模型专属分组
52
52
  3. `Account`
53
53
 
54
- 不同额度域的窗口不会交错。需要刷新时再次运行 `/usage` 即可;命令不会显示刷新、切换提供商或查询所有提供商的菜单。
54
+ 不同额度域的窗口不会交错。存在邮箱字段时,Codex `Account` 区域会显示从当前 OAuth Token 本地解析出的邮箱。需要刷新时再次运行 `/usage` 即可;命令不会显示刷新、切换提供商或查询所有提供商的菜单。
55
55
 
56
56
  只有当 Codex 返回可兑换的重置次数时,才会显示重置菜单。Grok 当前 API 只公开额度窗口和自然重置时间,没有经过验证的手动重置端点或重置次数,因此本扩展不会虚构重置操作。Grok 窗口仍通过与 Codex、OpenCode Go、Kimi 相同的 `/usage` 进度条和状态事件展示。
57
57
 
@@ -96,6 +96,7 @@ Codex 结果会按以下额度域分组:
96
96
  - Codex 重置还会通过公开的 `readStoredCredential()` API 读取 Pi 保存的 OAuth 凭据,仅用于确认其与当前运行时账户完全一致。
97
97
  - Grok 不会读取 `~/.grok/auth.json`,也不会用 API Key 代替订阅 OAuth。
98
98
  - 凭据不会写入缓存、会话、状态栏或错误消息;缓存键只保存进程内 HMAC 指纹。
99
+ - Codex 邮箱仅在本地解析后显示于 `/usage` 账户区域,不会进入底部状态或结构化状态事件。
99
100
  - 凭据只会发送到对应的官方域名;自定义代理和自定义基础 URL 会被拒绝。
100
101
  - Codex 重置是唯一的写操作。只有存在可兑换次数时才会显示,并且始终要求明确确认。
101
102
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@specode/pi-subscription-usage",
3
- "version": "0.2.2",
3
+ "version": "0.2.3",
4
4
  "description": "Show subscription quota and Codex reset credits for Codex, OpenCode Go, Grok, and Kimi in Pi",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/src/format.ts CHANGED
@@ -48,8 +48,12 @@ export function formatUsageReport(
48
48
  const grouped = sections.some((section) => Boolean(section.heading));
49
49
  const lines = [report.providerName];
50
50
  if (!grouped) {
51
- const rows = [...sections.flatMap((section) => section.rows), ...accountRows];
51
+ const rows = sections.flatMap((section) => section.rows);
52
52
  lines.push(...formatPanelRows(rows, labelWidth, 2));
53
+ if (accountRows.length > 0) {
54
+ lines.push("", " Account:");
55
+ lines.push(...formatPanelRows(accountRows, labelWidth, 4));
56
+ }
53
57
  return lines.join("\n");
54
58
  }
55
59
  for (const section of sections) {
@@ -9,6 +9,7 @@ import {
9
9
  export function normalizeCodexUsage(
10
10
  payload: unknown,
11
11
  capturedAt: number,
12
+ accountEmail?: string,
12
13
  ): UsageReport {
13
14
  const root = asObject(payload);
14
15
  if (!root) throw new Error("Codex usage response was not an object.");
@@ -74,8 +75,8 @@ export function normalizeCodexUsage(
74
75
  if (buckets.length === 0 && metrics.length === 0) {
75
76
  throw new Error("Codex usage endpoint returned no displayable usage data.");
76
77
  }
77
- const planType = asString(root.plan_type);
78
- if (planType) metrics.push({ id: "plan", label: "Plan", value: planType });
78
+ addAccountMetrics(metrics, accountEmail, root.plan_type);
79
+ sortAccountMetrics(metrics);
79
80
  return {
80
81
  providerId: CODEX_PROVIDER_ID,
81
82
  providerName: "OpenAI Codex",
@@ -91,6 +92,53 @@ export function normalizeCodexUsage(
91
92
  };
92
93
  }
93
94
 
95
+ export function codexEmailFromAuthorization(
96
+ authorization: string | undefined,
97
+ ): string | undefined {
98
+ const match = /^Bearer\s+(\S+)$/iu.exec(authorization?.trim() ?? "");
99
+ const accessToken = match?.[1];
100
+ if (!accessToken) return undefined;
101
+ try {
102
+ const parts = accessToken.split(".");
103
+ if (parts.length !== 3 || !parts[1]) return undefined;
104
+ const payload = asObject(
105
+ JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8")),
106
+ );
107
+ const profile = asObject(payload?.["https://api.openai.com/profile"]);
108
+ return asEmail(profile?.email) ?? asEmail(payload?.email);
109
+ } catch {
110
+ return undefined;
111
+ }
112
+ }
113
+
114
+ function addAccountMetrics(
115
+ metrics: UsageMetric[],
116
+ accountEmail: string | undefined,
117
+ planTypeValue: unknown,
118
+ ): void {
119
+ const email = asEmail(accountEmail);
120
+ if (email) metrics.unshift({ id: "email", label: "Email", value: email });
121
+ const planType = asString(planTypeValue);
122
+ if (!planType) return;
123
+ metrics.push({
124
+ id: "plan",
125
+ label: "Plan",
126
+ value: planType.toLowerCase() === "pro" ? "Pro" : planType,
127
+ });
128
+ }
129
+
130
+ function sortAccountMetrics(metrics: UsageMetric[]): void {
131
+ const order = ["email", "plan", "reset-credits", "credits"];
132
+ metrics.sort((left, right) => {
133
+ const leftRank = order.indexOf(left.id);
134
+ const rightRank = order.indexOf(right.id);
135
+ return (
136
+ (leftRank < 0 ? order.length : leftRank) -
137
+ (rightRank < 0 ? order.length : rightRank)
138
+ );
139
+ });
140
+ }
141
+
94
142
  function normalizeRateLimitGroup(
95
143
  buckets: UsageBucket[],
96
144
  groupId: string,
@@ -152,6 +200,12 @@ function asString(value: unknown): string | undefined {
152
200
  : undefined;
153
201
  }
154
202
 
203
+ function asEmail(value: unknown): string | undefined {
204
+ if (typeof value !== "string" || value.length > 254) return undefined;
205
+ const email = sanitizeDisplayText(value, 254).toLowerCase();
206
+ return /^[^\s@]+@[^\s@]+$/u.test(email) ? email : undefined;
207
+ }
208
+
155
209
  function asNumber(value: unknown): number | undefined {
156
210
  if (typeof value === "number" && Number.isFinite(value)) return value;
157
211
  if (typeof value === "string" && value.trim()) {
@@ -77,7 +77,9 @@ export function normalizeGrokBilling(
77
77
  if (weekly) buckets.push(weekly);
78
78
  if (monthly) buckets.push(monthly);
79
79
  if (buckets.length === 0) {
80
- throw new Error("Grok billing endpoint returned no displayable quota window.");
80
+ throw new Error(
81
+ "Grok billing endpoint returned no displayable quota window.",
82
+ );
81
83
  }
82
84
 
83
85
  const primaryMetrics = collectMetrics(creditsConfig);
@@ -1,5 +1,16 @@
1
1
  // Adapted from @sumhou/pi-kimi-usage@1.0.1 (MIT).
2
- import type { UsageBucket, UsageReport } from "../types.ts";
2
+ import { sanitizeDisplayText } from "../core.ts";
3
+ import type { UsageBucket, UsageMetric, UsageReport } from "../types.ts";
4
+
5
+ const MAX_PLAN_LEVEL_LENGTH = 80;
6
+ const KIMI_PLAN_NAMES: Readonly<Record<string, string>> = {
7
+ LEVEL_FREE: "Free",
8
+ LEVEL_BASIC: "Adagio",
9
+ LEVEL_STANDARD: "Moderato",
10
+ LEVEL_INTERMEDIATE: "Allegretto",
11
+ LEVEL_ADVANCED: "Allegro",
12
+ LEVEL_PREMIUM: "Vivace",
13
+ };
3
14
 
4
15
  export function normalizeKimiUsage(
5
16
  payload: unknown,
@@ -38,6 +49,9 @@ export function normalizeKimiUsage(
38
49
  if (buckets.length === 0) {
39
50
  throw new Error("Kimi usage endpoint returned no displayable quota data.");
40
51
  }
52
+ const metrics: UsageMetric[] = [];
53
+ const plan = kimiPlanName(root);
54
+ if (plan) metrics.push({ id: "plan", label: "Plan", value: plan });
41
55
  return {
42
56
  providerId: "kimi-coding",
43
57
  providerName: "Kimi Coding",
@@ -45,10 +59,20 @@ export function normalizeKimiUsage(
45
59
  source: "kimi-coding-usage",
46
60
  semantics: { kind: "consumer-subscription", label: "Kimi Coding plan usage" },
47
61
  buckets,
48
- metrics: [],
62
+ metrics,
49
63
  };
50
64
  }
51
65
 
66
+ function kimiPlanName(root: Record<string, unknown>): string | undefined {
67
+ const membership = asObject(asObject(root.user)?.membership);
68
+ if (typeof membership?.level !== "string") return undefined;
69
+ const level = sanitizeDisplayText(membership.level, MAX_PLAN_LEVEL_LENGTH);
70
+ if (!level) return undefined;
71
+ return Object.hasOwn(KIMI_PLAN_NAMES, level)
72
+ ? KIMI_PLAN_NAMES[level]
73
+ : level;
74
+ }
75
+
52
76
  function parseQuota(
53
77
  value: unknown,
54
78
  ): Omit<UsageBucket, "id" | "label" | "unit"> | undefined {
package/src/query.ts CHANGED
@@ -9,7 +9,10 @@ import {
9
9
  redactUsageError,
10
10
  } from "./core.ts";
11
11
  import { CODEX_PROVIDER_ID } from "./providers/codex-constants.ts";
12
- import { normalizeCodexUsage } from "./providers/codex.ts";
12
+ import {
13
+ codexEmailFromAuthorization,
14
+ normalizeCodexUsage,
15
+ } from "./providers/codex.ts";
13
16
  import {
14
17
  grokRequestHeaders,
15
18
  normalizeGrokBilling,
@@ -64,6 +67,7 @@ export const SUPPORTED_ADAPTERS: readonly UsageProviderAdapter[] = [
64
67
  "Codex usage endpoint",
65
68
  ),
66
69
  Date.now(),
70
+ codexEmailFromAuthorization(auth.headers.Authorization),
67
71
  );
68
72
  },
69
73
  },