@specode/pi-subscription-usage 0.1.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/LICENSE ADDED
@@ -0,0 +1,23 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 specode
4
+ Copyright (c) 2026 narumiruna
5
+ Copyright (c) 2026 puetsua
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ of this software and associated documentation files (the "Software"), to deal
9
+ in the Software without restriction, including without limitation the rights
10
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ copies of the Software, and to permit persons to whom the Software is
12
+ furnished to do so, subject to the following conditions:
13
+
14
+ The above copyright notice and this permission notice shall be included in all
15
+ copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,116 @@
1
+ # Pi Subscription Usage
2
+
3
+ [English](README.md) | [简体中文](README.zh-CN.md)
4
+
5
+ A Pi extension that shows the active account's subscription quota in one consistent view.
6
+
7
+ Supported providers:
8
+
9
+ - **OpenAI Codex** — 5-hour and weekly quota, model-specific quota, and confirmed reset-credit redemption.
10
+ - **OpenCode Go** — 5-hour, weekly, and monthly windows.
11
+ - **Grok** — weekly or monthly quota using only Pi's `xai` / `xai-auth` OAuth credentials, with account identity verification.
12
+ - **Kimi Coding** — 5-hour and weekly windows.
13
+
14
+ The extension does not implement or modify Codex Fast mode and never rewrites model requests.
15
+
16
+ ## Installation
17
+
18
+ Install directly from GitHub:
19
+
20
+ ```bash
21
+ pi install git:github.com/specode/pi-subscription-usage
22
+ ```
23
+
24
+ After the npm package is published, it can also be installed with:
25
+
26
+ ```bash
27
+ pi install npm:@specode/pi-subscription-usage
28
+ ```
29
+
30
+ For local development:
31
+
32
+ ```bash
33
+ pi install /absolute/path/to/pi-subscription-usage
34
+ ```
35
+
36
+ Pi packages execute with your full system permissions. Review third-party package source before installing it.
37
+
38
+ ## Usage
39
+
40
+ Run:
41
+
42
+ ```text
43
+ /usage
44
+ ```
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.
47
+
48
+ Codex results are grouped by quota domain in this order:
49
+
50
+ 1. `Shared Across Models`
51
+ 2. Model-specific sections
52
+ 3. `Account`
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.
55
+
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.
57
+
58
+ ## Codex reset safety
59
+
60
+ Before redeeming a Codex reset credit, the extension:
61
+
62
+ 1. Verifies that the active model is still using Codex.
63
+ 2. Verifies that the runtime token exactly matches the OAuth account stored by Pi through `/login`.
64
+ 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.
65
+ 4. Uses a unique request ID and reuses it across retries.
66
+
67
+ ## Status integration
68
+
69
+ The extension publishes two status layers:
70
+
71
+ - A plain `setStatus` string without provider names or icons, such as `5h 99% · 1w 85% · 1m 60%`.
72
+ - Structured window data through the `subscription-usage/status/v1` event.
73
+
74
+ 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.
75
+
76
+ ## Security boundaries
77
+
78
+ - Usage queries resolve credentials only through `ctx.modelRegistry.getProviderAuth()`.
79
+ - 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.
80
+ - Grok never reads `~/.grok/auth.json` and never accepts an API key in place of subscription OAuth.
81
+ - Credentials are never written to caches, sessions, the status line, or error messages. Cache keys contain only in-process HMAC fingerprints.
82
+ - Credentials are sent only to the corresponding official domains. Custom proxies and custom base URLs are rejected.
83
+ - Codex reset is the only write operation. It is shown only when redeemable credits exist and always requires explicit confirmation.
84
+
85
+ ## Development
86
+
87
+ Requirements:
88
+
89
+ - A current Pi installation.
90
+ - A Node.js version that can run TypeScript files directly for the test suite.
91
+
92
+ Run the tests:
93
+
94
+ ```bash
95
+ npm test
96
+ ```
97
+
98
+ Inspect the npm package contents:
99
+
100
+ ```bash
101
+ npm run pack:check
102
+ ```
103
+
104
+ Load the extension directly without installing it:
105
+
106
+ ```bash
107
+ pi --no-extensions --offline -e ./index.ts --list-models
108
+ ```
109
+
110
+ ## Stability
111
+
112
+ 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.
113
+
114
+ ## License
115
+
116
+ [MIT](LICENSE). See [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md) for adapted third-party sources and licenses.
@@ -0,0 +1,116 @@
1
+ # Pi Subscription Usage
2
+
3
+ [English](README.md) | [简体中文](README.zh-CN.md)
4
+
5
+ 一个用统一格式展示当前 Pi 账户订阅额度的扩展。
6
+
7
+ 支持以下提供商:
8
+
9
+ - **OpenAI Codex**:5 小时与每周额度、模型专属额度,以及需要确认的重置次数兑换。
10
+ - **OpenCode Go**:5 小时、每周和每月窗口。
11
+ - **Grok**:每周或每月额度;只使用 Pi 的 `xai` / `xai-auth` OAuth 凭据,并先验证账户身份。
12
+ - **Kimi Coding**:5 小时和每周窗口。
13
+
14
+ 本扩展不实现或修改 Codex Fast 模式,也不会改写模型请求。
15
+
16
+ ## 安装
17
+
18
+ 直接从 GitHub 安装:
19
+
20
+ ```bash
21
+ pi install git:github.com/specode/pi-subscription-usage
22
+ ```
23
+
24
+ npm 包发布后,也可以这样安装:
25
+
26
+ ```bash
27
+ pi install npm:@specode/pi-subscription-usage
28
+ ```
29
+
30
+ 本地开发时可以安装本地目录:
31
+
32
+ ```bash
33
+ pi install /absolute/path/to/pi-subscription-usage
34
+ ```
35
+
36
+ Pi package 拥有当前用户的完整系统权限。安装第三方 package 前,请先审查其源码。
37
+
38
+ ## 使用
39
+
40
+ 运行:
41
+
42
+ ```text
43
+ /usage
44
+ ```
45
+
46
+ 每次调用都会跳过缓存并重新查询当前提供商。所有额度窗口都使用统一格式,并以 `MM/DD HH:mm` 显示重置时间。
47
+
48
+ Codex 结果会按以下额度域分组:
49
+
50
+ 1. `Shared Across Models`
51
+ 2. 各模型专属分组
52
+ 3. `Account`
53
+
54
+ 不同额度域的窗口不会交错。需要刷新时再次运行 `/usage` 即可;命令不会显示刷新、切换提供商或查询所有提供商的菜单。
55
+
56
+ 只有当 Codex 返回可兑换的重置次数时,才会显示重置菜单。Grok 当前 API 只公开额度窗口和自然重置时间,没有经过验证的手动重置端点或重置次数,因此本扩展不会虚构重置操作。
57
+
58
+ ## Codex 重置安全措施
59
+
60
+ 兑换 Codex 重置次数前,本扩展会:
61
+
62
+ 1. 确认当前模型仍在使用 Codex。
63
+ 2. 确认运行时令牌与 Pi 通过 `/login` 保存的 OAuth 账户完全一致。
64
+ 3. 显示即将消耗的重置次数并要求明确确认。`Cancel (Default)` 始终位于第一项;只有主动选择第二项才会继续。
65
+ 4. 使用唯一请求 ID,并在重试时复用同一个 ID。
66
+
67
+ ## 状态集成
68
+
69
+ 本扩展提供两层状态输出:
70
+
71
+ - 不含提供商名称或图标的普通 `setStatus` 文本,例如 `5h 99% · 1w 85% · 1m 60%`。
72
+ - 通过 `subscription-usage/status/v1` 事件发布的结构化窗口数据。
73
+
74
+ 窗口始终按 `5h / 1w / 1m / other` 排序。其他扩展可以直接消费结构化事件,自定义图标、颜色和布局,而不必解析显示文本。
75
+
76
+ ## 安全边界
77
+
78
+ - 额度查询只通过 `ctx.modelRegistry.getProviderAuth()` 解析凭据。
79
+ - Codex 重置还会通过公开的 `readStoredCredential()` API 读取 Pi 保存的 OAuth 凭据,仅用于确认其与当前运行时账户完全一致。
80
+ - Grok 不会读取 `~/.grok/auth.json`,也不会用 API Key 代替订阅 OAuth。
81
+ - 凭据不会写入缓存、会话、状态栏或错误消息;缓存键只保存进程内 HMAC 指纹。
82
+ - 凭据只会发送到对应的官方域名;自定义代理和自定义基础 URL 会被拒绝。
83
+ - Codex 重置是唯一的写操作。只有存在可兑换次数时才会显示,并且始终要求明确确认。
84
+
85
+ ## 开发
86
+
87
+ 要求:
88
+
89
+ - 当前版本的 Pi。
90
+ - 能够直接运行 TypeScript 文件的 Node.js 版本,用于执行测试。
91
+
92
+ 运行测试:
93
+
94
+ ```bash
95
+ npm test
96
+ ```
97
+
98
+ 检查 npm 包内容:
99
+
100
+ ```bash
101
+ npm run pack:check
102
+ ```
103
+
104
+ 不安装、直接加载扩展:
105
+
106
+ ```bash
107
+ pi --no-extensions --offline -e ./index.ts --list-models
108
+ ```
109
+
110
+ ## 稳定性
111
+
112
+ Codex 重置、Grok 账单和 Kimi 额度依赖未公开的提供商 API,这些 API 可能发生变化。如果 API 调用失败,本扩展只会报告查询错误,不会退回到不受控制的凭据或代理路径。
113
+
114
+ ## 许可证
115
+
116
+ 采用 [MIT](LICENSE) 许可证。改编的第三方源码及其许可证见 [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md)。
@@ -0,0 +1,22 @@
1
+ # Third-party notices
2
+
3
+ This package selectively adapts MIT-licensed implementation ideas and source
4
+ from the following projects. The original copyright notices and MIT permission
5
+ notice are retained in `LICENSE`.
6
+
7
+ - `@narumitw/pi-usage` 0.53.0
8
+ - Copyright (c) 2026 narumiruna
9
+ - <https://github.com/narumiruna/pi-extensions/tree/main/packages/pi-usage>
10
+ - Adapted areas: usage model, cache/redaction helpers, Codex and OpenCode Go
11
+ normalization, runtime-auth origin checks, and Codex reset flow.
12
+ - `pi-grok-usage` 1.0.4
13
+ - Copyright (c) 2026 puetsua
14
+ - <https://github.com/puetsua/pi-grok-usage>
15
+ - Adapted areas: identity-first Grok billing lookup and bounded response
16
+ normalization.
17
+ - `@sumhou/pi-kimi-usage` 1.0.1
18
+ - MIT license
19
+ - <https://github.com/ShumaoHou/pi-kimi-usage>
20
+ - Adapted areas: Kimi Coding quota response normalization.
21
+
22
+ No third-party package is bundled as a runtime dependency.
package/index.ts ADDED
@@ -0,0 +1 @@
1
+ export { default } from "./src/usage.ts";
package/package.json ADDED
@@ -0,0 +1,51 @@
1
+ {
2
+ "name": "@specode/pi-subscription-usage",
3
+ "version": "0.1.0",
4
+ "description": "Show subscription quota and Codex reset credits for Codex, OpenCode Go, Grok, and Kimi in Pi",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "author": "Specode",
8
+ "homepage": "https://github.com/specode/pi-subscription-usage#readme",
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/specode/pi-subscription-usage.git"
12
+ },
13
+ "bugs": {
14
+ "url": "https://github.com/specode/pi-subscription-usage/issues"
15
+ },
16
+ "keywords": [
17
+ "pi-package",
18
+ "pi-extension",
19
+ "subscription",
20
+ "usage",
21
+ "quota",
22
+ "codex",
23
+ "opencode",
24
+ "grok",
25
+ "kimi"
26
+ ],
27
+ "files": [
28
+ "index.ts",
29
+ "src",
30
+ "README.md",
31
+ "README.zh-CN.md",
32
+ "LICENSE",
33
+ "THIRD_PARTY_NOTICES.md"
34
+ ],
35
+ "pi": {
36
+ "extensions": [
37
+ "./index.ts"
38
+ ]
39
+ },
40
+ "scripts": {
41
+ "test": "node --test test/*.test.ts",
42
+ "pack:check": "npm pack --dry-run",
43
+ "prepublishOnly": "npm test"
44
+ },
45
+ "peerDependencies": {
46
+ "@earendil-works/pi-coding-agent": "*"
47
+ },
48
+ "publishConfig": {
49
+ "access": "public"
50
+ }
51
+ }
@@ -0,0 +1,249 @@
1
+ // Adapted from @narumitw/pi-usage@0.53.0 (MIT).
2
+ import { sanitizeDisplayText } from "./core.ts";
3
+ import type { UsageReport } from "./types.ts";
4
+
5
+ export type CodexResetOutcomeCode =
6
+ | "reset"
7
+ | "nothing_to_reset"
8
+ | "no_credit"
9
+ | "already_redeemed";
10
+
11
+ export interface CodexResetOption {
12
+ creditId?: string;
13
+ title: string;
14
+ description: string;
15
+ expiresAt?: number;
16
+ }
17
+
18
+ export interface CodexResetAvailability {
19
+ availableCount: number;
20
+ options: CodexResetOption[];
21
+ }
22
+
23
+ export interface CodexResetOutcome {
24
+ code: CodexResetOutcomeCode;
25
+ windowsReset: number;
26
+ }
27
+
28
+ export const CODEX_RESET_CONFIRMATION_OPTIONS = [
29
+ "Cancel (Default)",
30
+ "Redeem 1 Reset (Irreversible)",
31
+ ] as const;
32
+
33
+ export function isCodexResetConfirmed(value: string | undefined): boolean {
34
+ return value === CODEX_RESET_CONFIRMATION_OPTIONS[1];
35
+ }
36
+
37
+ export function codexResetCount(report: UsageReport): number | undefined {
38
+ const value = report.metrics.find(
39
+ (metric) => metric.id === "reset-credits",
40
+ )?.value;
41
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0
42
+ ? value
43
+ : undefined;
44
+ }
45
+
46
+ export function genericCodexResetOption(): CodexResetOption {
47
+ return {
48
+ title: "Full Reset",
49
+ description: "Resets the current usage windows.",
50
+ };
51
+ }
52
+
53
+ export function resetOptionExpiration(option: CodexResetOption): string {
54
+ if (option.expiresAt === undefined) return "No Expiry";
55
+ const expiration = new Date(option.expiresAt * 1_000);
56
+ return Number.isNaN(expiration.getTime())
57
+ ? "Expiry Unavailable"
58
+ : `Expires ${expiration.toLocaleString("en-US")}`;
59
+ }
60
+
61
+ export function formatCodexResetOutcome(
62
+ outcome: CodexResetOutcome | undefined,
63
+ remainingCount: number | undefined,
64
+ ): string {
65
+ const remaining =
66
+ remainingCount === undefined ? "" : `, ${remainingCount} left`;
67
+ if (!outcome) return "No reset credits available.";
68
+ if (outcome.code === "reset") return `Reset redeemed${remaining}.`;
69
+ if (outcome.code === "already_redeemed") {
70
+ return `Reset already redeemed${remaining}.`;
71
+ }
72
+ if (outcome.code === "nothing_to_reset") return "Nothing to reset right now.";
73
+ return "No reset credits available.";
74
+ }
75
+
76
+ export function verifyCodexStoredOAuthCredential(
77
+ resolvedAccess: string,
78
+ storedCredential: unknown,
79
+ ): string {
80
+ const resolvedAccountId = codexAccountIdFromAccessToken(resolvedAccess);
81
+ if (!resolvedAccountId) {
82
+ throw new Error(
83
+ "The active OpenAI Codex access token did not contain a valid account ID.",
84
+ );
85
+ }
86
+ const credential = asObject(storedCredential);
87
+ if (credential?.type !== "oauth") {
88
+ throw new Error(
89
+ "Codex resets require the OAuth account configured through Pi /login.",
90
+ );
91
+ }
92
+ const storedAccess = nonemptyString(credential.access);
93
+ const accountId = validHeaderValue(credential.accountId);
94
+ const refresh = nonemptyString(credential.refresh);
95
+ if (
96
+ storedAccess !== resolvedAccess ||
97
+ !accountId ||
98
+ accountId !== resolvedAccountId ||
99
+ !refresh
100
+ ) {
101
+ throw new Error(
102
+ "The active Codex runtime account does not match Pi's stored OAuth account.",
103
+ );
104
+ }
105
+ return accountId;
106
+ }
107
+
108
+ export function normalizeCodexResetCreditsPayload(
109
+ payload: Record<string, unknown>,
110
+ ): CodexResetAvailability {
111
+ const availableCount = nonnegativeInteger(payload.available_count);
112
+ if (availableCount === undefined) {
113
+ throw new Error(
114
+ "Codex reset credits response returned an invalid available_count.",
115
+ );
116
+ }
117
+ if (payload.credits !== undefined && !Array.isArray(payload.credits)) {
118
+ throw new Error("Codex reset credits response returned invalid credits.");
119
+ }
120
+ const options: CodexResetOption[] = [];
121
+ for (const rawCredit of payload.credits ?? []) {
122
+ const credit = asObject(rawCredit);
123
+ if (
124
+ !credit ||
125
+ credit.status !== "available" ||
126
+ credit.reset_type !== "codex_rate_limits"
127
+ ) {
128
+ continue;
129
+ }
130
+ options.push(normalizeResetOption(credit));
131
+ }
132
+ options.sort(
133
+ (left, right) =>
134
+ (left.expiresAt ?? Number.MAX_SAFE_INTEGER) -
135
+ (right.expiresAt ?? Number.MAX_SAFE_INTEGER),
136
+ );
137
+ options.splice(Math.min(availableCount, 32));
138
+ if (availableCount > 0 && options.length === 0)
139
+ options.push(genericCodexResetOption());
140
+ return { availableCount, options };
141
+ }
142
+
143
+ export function parseCodexResetOutcome(
144
+ payload: Record<string, unknown>,
145
+ ): CodexResetOutcome {
146
+ const code = payload.code;
147
+ if (!isOutcomeCode(code)) {
148
+ throw new Error(
149
+ "Codex reset consume endpoint returned an unknown outcome code.",
150
+ );
151
+ }
152
+ const windowsReset =
153
+ payload.windows_reset === undefined
154
+ ? 0
155
+ : nonnegativeInteger(payload.windows_reset);
156
+ if (windowsReset === undefined) {
157
+ throw new Error(
158
+ "Codex reset consume endpoint returned an invalid windows_reset value.",
159
+ );
160
+ }
161
+ return { code, windowsReset };
162
+ }
163
+
164
+ function normalizeResetOption(
165
+ credit: Record<string, unknown>,
166
+ ): CodexResetOption {
167
+ const creditId = opaqueId(credit.id);
168
+ if (!creditId)
169
+ throw new Error(
170
+ "Codex reset credits response returned an invalid credit ID.",
171
+ );
172
+ let expiresAt: number | undefined;
173
+ if (credit.expires_at !== undefined && credit.expires_at !== null) {
174
+ if (typeof credit.expires_at !== "string") {
175
+ throw new Error(
176
+ "Codex reset credits response returned an invalid expiration time.",
177
+ );
178
+ }
179
+ const parsed = Date.parse(credit.expires_at);
180
+ if (!Number.isFinite(parsed)) {
181
+ throw new Error(
182
+ "Codex reset credits response returned an invalid expiration time.",
183
+ );
184
+ }
185
+ expiresAt = Math.floor(parsed / 1_000);
186
+ }
187
+ return {
188
+ creditId,
189
+ title: displayString(credit.title) ?? "Full Reset",
190
+ description:
191
+ displayString(credit.description) ?? "Resets the current usage windows.",
192
+ ...(expiresAt === undefined ? {} : { expiresAt }),
193
+ };
194
+ }
195
+
196
+ function isOutcomeCode(value: unknown): value is CodexResetOutcomeCode {
197
+ return ["reset", "nothing_to_reset", "no_credit", "already_redeemed"].includes(
198
+ value as string,
199
+ );
200
+ }
201
+
202
+ function codexAccountIdFromAccessToken(access: string): string | undefined {
203
+ try {
204
+ const parts = access.split(".");
205
+ if (parts.length !== 3 || !parts[1]) return undefined;
206
+ const payload = JSON.parse(
207
+ Buffer.from(parts[1], "base64url").toString("utf8"),
208
+ ) as unknown;
209
+ const claims = asObject(asObject(payload)?.["https://api.openai.com/auth"]);
210
+ return validHeaderValue(claims?.chatgpt_account_id);
211
+ } catch {
212
+ return undefined;
213
+ }
214
+ }
215
+
216
+ function asObject(value: unknown): Record<string, unknown> | undefined {
217
+ return value && typeof value === "object" && !Array.isArray(value)
218
+ ? (value as Record<string, unknown>)
219
+ : undefined;
220
+ }
221
+
222
+ function nonemptyString(value: unknown): string | undefined {
223
+ return typeof value === "string" && value.length > 0 ? value : undefined;
224
+ }
225
+
226
+ function validHeaderValue(value: unknown): string | undefined {
227
+ if (typeof value !== "string" || !value || value.length > 512)
228
+ return undefined;
229
+ return /[^\x20-\x7e]/u.test(value) ? undefined : value;
230
+ }
231
+
232
+ function opaqueId(value: unknown): string | undefined {
233
+ return typeof value === "string" && value.length > 0 && value.length <= 1_024
234
+ ? value
235
+ : undefined;
236
+ }
237
+
238
+ function displayString(value: unknown): string | undefined {
239
+ return typeof value === "string"
240
+ ? sanitizeDisplayText(value, 160) || undefined
241
+ : undefined;
242
+ }
243
+
244
+ function nonnegativeInteger(value: unknown): number | undefined {
245
+ let parsed = Number.NaN;
246
+ if (typeof value === "number") parsed = value;
247
+ else if (typeof value === "string" && value.trim()) parsed = Number(value);
248
+ return Number.isSafeInteger(parsed) && parsed >= 0 ? parsed : undefined;
249
+ }