pi-usage-lite 0.0.0-stage → 1.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/CHANGELOG.md ADDED
@@ -0,0 +1,28 @@
1
+ # Changelog
2
+
3
+ All notable changes to pi-usage-lite are documented here. This project follows [Semantic Versioning](https://semver.org/).
4
+
5
+ ## [1.0.0]
6
+
7
+ First stable release. The `/usage` and `/usage-all` commands, the `usage-zen.json` file, and the `OPENCODE_ZEN_*` environment variables are now covered by semantic versioning.
8
+
9
+ ### Changed
10
+
11
+ - Usage now has its own row below the editor instead of sharing Pi's footer status line with other extensions.
12
+
13
+ ### Fixed
14
+
15
+ - Expired Claude Code OAuth tokens are renewed before fetching usage, instead of failing until Claude Code next runs.
16
+ - The Kimi five-hour bar stays visible while the session window is briefly missing from API responses around a reset.
17
+ - `/usage-all` no longer lists providers whose usage request fails, such as an OpenCode Zen dashboard cookie that has expired.
18
+
19
+ ## [0.1.1]
20
+
21
+ ### Changed
22
+
23
+ - Kimi uses the same display format as Codex and Claude: window label, usage bar, used percentage, and reset countdown.
24
+ - OpenCode Zen credits are shown as numbers only, without a usage bar.
25
+
26
+ ## [0.1.0]
27
+
28
+ - Initial release.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 HossinAmin
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,157 @@
1
- # Temporary Holding Version
1
+ # pi-usage-lite
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![npm version](https://img.shields.io/npm/v/pi-usage-lite)](https://www.npmjs.com/package/pi-usage-lite)
4
+ [![npm downloads](https://img.shields.io/npm/d18m/pi-usage-lite)](https://www.npmjs.com/package/pi-usage-lite)
5
+ [![CI](https://github.com/HossinAmin/pi-usage-lite/actions/workflows/ci.yml/badge.svg)](https://github.com/HossinAmin/pi-usage-lite/actions/workflows/ci.yml)
6
+ [![License: MIT](https://img.shields.io/npm/l/pi-usage-lite)](./LICENSE)
7
+
8
+ A minimal, dependency-free [Pi Coding Agent](https://pi.dev) extension that keeps selected provider usage and quota information visible in a dedicated row below the editor.
9
+
10
+ ```text
11
+ claude claude-sonnet-4-5 · 5h [██░░░░░░] 23% ↻2h14m · wk [█░░░░░░░] 12% ↻4d3h
12
+ ```
13
+
14
+ The extension is intentionally small: one TypeScript file, no runtime package dependencies, automatic display refreshes, and two commands.
15
+
16
+ **Packages:** [Pi package](https://pi.dev/packages/pi-usage-lite) · [npm package](https://www.npmjs.com/package/pi-usage-lite)
17
+
18
+ ## Install
19
+
20
+ Install the latest release from npm using Pi:
21
+
22
+ ```bash
23
+ pi install npm:pi-usage-lite
24
+ ```
25
+
26
+ Then restart Pi or run:
27
+
28
+ ```text
29
+ /reload
30
+ ```
31
+
32
+ To pin a specific version, use an exact npm version:
33
+
34
+ ```bash
35
+ pi install npm:pi-usage-lite@1.0.0
36
+ ```
37
+
38
+ ## Features
39
+
40
+ - Shows usage in its own row below Pi's editor for the active model provider, keeping it separate from other extensions' footer statuses without replacing Pi's footer.
41
+ - Refreshes when a session starts, when the model changes, after each agent run, and every 60 seconds.
42
+ - Keeps the last known values visible when a later refresh fails.
43
+ - Provides `/usage` to refresh the active provider.
44
+ - Provides `/usage-all` to show usage for every supported provider currently connected to Pi.
45
+
46
+ ## Supported providers
47
+
48
+ | Provider | Information shown |
49
+ | --- | --- |
50
+ | Kimi for Coding | Five-hour and weekly plan windows |
51
+ | OpenAI Codex | Available rate-limit windows and reset times |
52
+ | Claude Code Bridge | Five-hour, weekly, Opus, Sonnet, and extra-usage information when available |
53
+ | OpenCode Zen | Numeric credit balance and spending information |
54
+
55
+ The row shows the active model's provider. Example rows for each provider:
56
+
57
+ ```text
58
+ kimi kimi-k2 · 5h [███░░░░░] 42% ↻2h30m · wk [█░░░░░░░] 10% ↻3d0h
59
+ codex gpt-5.5 · 5h [██░░░░░░] 23% ↻2h14m · wk [█████░░░] 62% ↻4d3h
60
+ claude claude-sonnet-4-5 · 5h [██░░░░░░] 23% ↻2h14m · wk [█░░░░░░░] 12% ↻4d3h · extra 12.50/50.00 USD
61
+ zen grok-code · 75.00/100.00 credits · 25% used
62
+ ```
63
+
64
+ Quota-window providers use the same display style: window label, usage bar, used percentage, and time until the window resets (`↻`). OpenCode Zen remains numeric because it is credit-based rather than quota-based.
65
+
66
+ Provider data is shown only when Pi has compatible credentials configured.
67
+
68
+ ## Commands
69
+
70
+ ### `/usage`
71
+
72
+ Refreshes the usage row for the currently selected model's provider.
73
+
74
+ ### `/usage-all`
75
+
76
+ Checks every supported provider that appears connected and displays the available usage information in a notification.
77
+
78
+ ## OpenCode Zen dashboard fallback
79
+
80
+ The extension first tries OpenCode's official credits API using Pi's configured `opencode` provider credentials. Credit information is displayed numerically, without a quota bar.
81
+
82
+ If that API is unavailable, it can use an optional dashboard configuration. Create this file only if you need the fallback:
83
+
84
+ ```text
85
+ ~/.pi/agent/usage-zen.json
86
+ ```
87
+
88
+ Example shape:
89
+
90
+ ```json
91
+ {
92
+ "workspaceId": "your-workspace-id",
93
+ "authCookie": "your-open-code-auth-cookie"
94
+ }
95
+ ```
96
+
97
+ The `authCookie` is a sensitive credential. Keep the file private:
98
+
99
+ ```bash
100
+ chmod 600 ~/.pi/agent/usage-zen.json
101
+ ```
102
+
103
+ Do not commit this file. It is listed in this repository's `.gitignore` in case it is accidentally copied into a checkout.
104
+
105
+ You can also provide the fallback configuration through environment variables:
106
+
107
+ ```bash
108
+ export OPENCODE_ZEN_WORKSPACE_ID="your-workspace-id"
109
+ export OPENCODE_ZEN_AUTH_COOKIE="your-open-code-auth-cookie"
110
+ ```
111
+
112
+ ## Security and privacy
113
+
114
+ - This repository does not contain provider API keys, OAuth tokens, cookies, or workspace credentials.
115
+ - At runtime, the extension reads credentials from Pi's provider authentication, supported environment variables, Claude Code's OAuth configuration, or the optional local configuration files described above.
116
+ - Credentials are used only to request usage information from their corresponding provider endpoints.
117
+ - Like every Pi extension, this extension runs with your operating-system user permissions. Review the source before installing it.
118
+ - The OpenCode dashboard fallback relies on web-session cookies and undocumented page/server behavior. It is more fragile than the official credits API and may stop working after an OpenCode deployment.
119
+
120
+ ## Compatibility notes
121
+
122
+ - The extension registers `/usage`. Do not load it alongside another extension that registers the same command.
123
+ - Usage endpoints and response formats are provider-controlled, and some are undocumented. They may change without notice.
124
+ - The usage row displays the last successful value if a refresh fails, so values can be stale until the next successful refresh.
125
+ - The extension uses Pi's widget API below the editor and does not replace Pi's built-in footer renderer.
126
+ - This project is not affiliated with Pi, OpenAI, Anthropic, Moonshot AI, Kimi, or OpenCode.
127
+
128
+ ## Development
129
+
130
+ The extension source is [`src/index.ts`](./src/index.ts).
131
+
132
+ Useful local commands:
133
+
134
+ ```bash
135
+ # Install development dependencies
136
+ bun install
137
+
138
+ # Typecheck the extension and tests
139
+ bun run typecheck
140
+
141
+ # Run the tests
142
+ bun run test
143
+
144
+ # Try the package locally
145
+ pi -e .
146
+
147
+ # Inspect the extension source
148
+ ${EDITOR:-nano} src/index.ts
149
+ ```
150
+
151
+ There is no build step for users; Pi loads the TypeScript source through Jiti. Development dependencies are used only for local typechecking, tests, and release validation.
152
+
153
+ The tests in [`tests/`](./tests) load the extension into a fake Pi session with mocked provider responses. They run sandboxed: credential and config paths point at a temporary directory, and real network requests are blocked.
154
+
155
+ ## License
156
+
157
+ [MIT](./LICENSE)
package/package.json CHANGED
@@ -1,6 +1,61 @@
1
1
  {
2
2
  "name": "pi-usage-lite",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "A minimal Pi Coding Agent extension that shows Claude, Codex, Kimi, and OpenCode Zen usage limits in a row below the editor.",
5
+ "type": "module",
6
+ "types": "./src/index.ts",
7
+ "license": "MIT",
8
+ "author": {
9
+ "name": "HossinAmin",
10
+ "email": "hossinamin70@gmail.com"
11
+ },
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "https://github.com/HossinAmin/pi-usage-lite.git"
15
+ },
16
+ "homepage": "https://github.com/HossinAmin/pi-usage-lite#readme",
17
+ "bugs": {
18
+ "url": "https://github.com/HossinAmin/pi-usage-lite/issues"
19
+ },
20
+ "keywords": [
21
+ "pi-package",
22
+ "pi-extension",
23
+ "pi",
24
+ "pi-coding-agent",
25
+ "usage",
26
+ "quota",
27
+ "statusline",
28
+ "codex",
29
+ "kimi",
30
+ "claude",
31
+ "opencode"
32
+ ],
33
+ "files": [
34
+ "src",
35
+ "README.md",
36
+ "CHANGELOG.md",
37
+ "LICENSE"
38
+ ],
39
+ "pi": {
40
+ "extensions": [
41
+ "./src/index.ts"
42
+ ]
43
+ },
44
+ "publishConfig": {
45
+ "access": "public"
46
+ },
47
+ "peerDependencies": {
48
+ "@earendil-works/pi-coding-agent": "*"
49
+ },
50
+ "devDependencies": {
51
+ "@earendil-works/pi-coding-agent": "1.0.4",
52
+ "@types/bun": "^1.4.5",
53
+ "@types/node": "^26.6.4",
54
+ "typescript": "^7.0.2"
55
+ },
56
+ "scripts": {
57
+ "typecheck": "tsc --noEmit && tsc --noEmit -p tests",
58
+ "test": "bun test"
59
+ },
60
+ "packageManager": "bun@1.3.14"
61
+ }
package/src/index.ts ADDED
@@ -0,0 +1,684 @@
1
+ /**
2
+ * Usage Extension
3
+ *
4
+ * Shows provider usage/quota in a dedicated row below the editor. Currently supports Kimi for
5
+ * Coding (5-hour + weekly quotas), OpenAI Codex (its available rate-limit
6
+ * windows), Claude Code Bridge (Claude plan windows), and OpenCode Zen credits.
7
+ * The status only appears while the active
8
+ * model belongs to a supported provider. `/usage-all` shows quota information
9
+ * for every supported plan currently connected to pi.
10
+ *
11
+ * Updates after every prompt completion (agent_settled) and every 60s.
12
+ *
13
+ * To add more providers later, push another entry into USAGE_PROVIDERS.
14
+ */
15
+
16
+ import { Buffer } from "node:buffer";
17
+ import { readFile, writeFile } from "node:fs/promises";
18
+ import { homedir } from "node:os";
19
+ import { join } from "node:path";
20
+ import { getAgentDir, type ExtensionAPI, type ExtensionContext } from "@earendil-works/pi-coding-agent";
21
+
22
+ const STATUS_ID = "usage";
23
+ const REFRESH_MS = 60_000;
24
+
25
+ // ---------------------------------------------------------------------------
26
+ // Helpers
27
+ // ---------------------------------------------------------------------------
28
+
29
+ function fmtDuration(ms: number): string {
30
+ if (!Number.isFinite(ms)) return "?";
31
+ if (ms <= 0) return "now";
32
+ const m = Math.floor(ms / 60000);
33
+ if (m < 60) return `${m}m`;
34
+ const h = Math.floor(m / 60);
35
+ if (h < 24) return `${h}h${m % 60}m`;
36
+ const d = Math.floor(h / 24);
37
+ return `${d}d${h % 24}h`;
38
+ }
39
+
40
+ function fmtCountdown(resetIso: string): string {
41
+ return fmtDuration(new Date(resetIso).getTime() - Date.now());
42
+ }
43
+
44
+ // ---------------------------------------------------------------------------
45
+ // Provider handlers
46
+ // ---------------------------------------------------------------------------
47
+
48
+ interface UsageProvider {
49
+ /** Provider id used to resolve authentication. */
50
+ providerId: string;
51
+ /** Short label shown in the usage row and command output. */
52
+ label: string;
53
+ /** Return true if this handler serves the given provider id. */
54
+ matches(provider: string): boolean;
55
+ /** Optional custom connection check for providers with extra credentials. */
56
+ connected?(ctx: ExtensionContext): Promise<boolean>;
57
+ /** Fetch and format the usage text, or undefined on failure. */
58
+ fetch(ctx: ExtensionContext): Promise<string | undefined>;
59
+ }
60
+
61
+ async function isConnected(handler: UsageProvider, ctx: ExtensionContext): Promise<boolean> {
62
+ if (handler.connected) return handler.connected(ctx);
63
+ const result = await ctx.modelRegistry.getProviderAuth(handler.providerId);
64
+ if (result?.auth?.apiKey) return true;
65
+ return Object.keys(result?.auth?.headers ?? {}).some((key) => key.toLowerCase() === "authorization");
66
+ }
67
+
68
+ interface KimiQuotaDetail {
69
+ limit?: string;
70
+ used?: string;
71
+ remaining?: string;
72
+ resetTime?: string;
73
+ }
74
+
75
+ interface KimiRatioWindow {
76
+ used_ratio?: number;
77
+ reset_time?: string;
78
+ }
79
+
80
+ interface KimiUsagesResponse {
81
+ usage?: KimiQuotaDetail; // weekly quota (legacy shape)
82
+ limits?: Array<{
83
+ window?: { duration?: number; timeUnit?: string };
84
+ detail?: KimiQuotaDetail; // session window (legacy shape, omitted while no window is active)
85
+ }>;
86
+ usages?: {
87
+ limit_5h?: KimiRatioWindow; // session (5-hour) window
88
+ limit_7d?: KimiRatioWindow; // weekly quota
89
+ };
90
+ }
91
+
92
+ function parseKimiCount(value: string | undefined): number | undefined {
93
+ if (!value) return undefined;
94
+ const parsed = Number(value.replace(/,/g, ""));
95
+ return Number.isFinite(parsed) && parsed >= 0 ? parsed : undefined;
96
+ }
97
+
98
+ function formatKimiWindow(label: string, detail: KimiQuotaDetail | undefined): string | undefined {
99
+ const used = parseKimiCount(detail?.used);
100
+ const limit = parseKimiCount(detail?.limit);
101
+ if (used === undefined || limit === undefined || limit <= 0) return undefined;
102
+ const percent = Math.round((used / limit) * 100);
103
+ return `${label} ${progressBar(percent)} ${percent}% ↻${fmtCountdown(detail?.resetTime ?? "")}`;
104
+ }
105
+
106
+ function formatKimiRatioWindow(label: string, window: KimiRatioWindow | undefined): string | undefined {
107
+ if (typeof window?.used_ratio !== "number" || !Number.isFinite(window.used_ratio)) return undefined;
108
+ const percent = Math.round(window.used_ratio * 100);
109
+ return `${label} ${progressBar(percent)} ${percent}% ↻${window.reset_time ? fmtCountdown(window.reset_time) : "?"}`;
110
+ }
111
+
112
+ // Find the 5-hour session window by its duration instead of assuming limits[0].
113
+ function kimiSessionDetail(limits: KimiUsagesResponse["limits"]): KimiQuotaDetail | undefined {
114
+ if (!limits || limits.length === 0) return undefined;
115
+ const isSessionWindow = (entry: { window?: { duration?: number; timeUnit?: string } }): boolean => {
116
+ const duration = entry.window?.duration;
117
+ const unit = entry.window?.timeUnit ?? "";
118
+ if (typeof duration !== "number") return false;
119
+ if (/MINUTE/i.test(unit)) return duration >= 4 * 60 && duration <= 6 * 60;
120
+ if (/HOUR/i.test(unit)) return duration >= 4 && duration <= 6;
121
+ return false;
122
+ };
123
+ return (limits.find(isSessionWindow) ?? limits[0])?.detail;
124
+ }
125
+
126
+ // The session window briefly disappears from API responses around resets.
127
+ // Keep rendering the last known window until its reset time passes.
128
+ let kimiSessionCache: { percent: number; resetTime?: string } | undefined;
129
+
130
+ function cacheKimiSession(percent: number, resetTime?: string): void {
131
+ kimiSessionCache = { percent, resetTime };
132
+ }
133
+
134
+ function renderKimiSession(): string | undefined {
135
+ if (!kimiSessionCache?.resetTime) return undefined;
136
+ const resetMs = Date.parse(kimiSessionCache.resetTime);
137
+ if (!Number.isFinite(resetMs) || resetMs <= Date.now()) return undefined;
138
+ return `5h ${progressBar(kimiSessionCache.percent)} ${kimiSessionCache.percent}% ↻${fmtCountdown(kimiSessionCache.resetTime)}`;
139
+ }
140
+
141
+ const kimiCoding: UsageProvider = {
142
+ providerId: "kimi-coding",
143
+ label: "kimi",
144
+ matches: (provider) => /kimi/i.test(provider),
145
+ async fetch(ctx) {
146
+ const result = await ctx.modelRegistry.getProviderAuth("kimi-coding");
147
+ const apiKey = result?.auth?.apiKey;
148
+ const authHeaders = result?.auth?.headers ?? {};
149
+ const hasAuthorization = Object.keys(authHeaders).some((key) => key.toLowerCase() === "authorization");
150
+ if (!apiKey && !hasAuthorization) return undefined;
151
+
152
+ const base = (result?.auth?.baseUrl ?? "https://api.kimi.com/coding").replace(/\/+$/, "");
153
+ const res = await fetch(`${base}/v1/usages`, {
154
+ headers: {
155
+ "User-Agent": "KimiCLI/1.5",
156
+ ...authHeaders,
157
+ // OAuth providers (including Kimi) supply Authorization in authHeaders.
158
+ // API-key providers use the fallback below.
159
+ ...(hasAuthorization || !apiKey ? {} : { Authorization: `Bearer ${apiKey}` }),
160
+ },
161
+ });
162
+ if (!res.ok) return undefined;
163
+
164
+ const data = (await res.json()) as KimiUsagesResponse;
165
+
166
+ // Prefer the ratio-based shape; fall back to the legacy count-based windows.
167
+ const ratio = data.usages?.limit_5h;
168
+ if (typeof ratio?.used_ratio === "number" && Number.isFinite(ratio.used_ratio)) {
169
+ cacheKimiSession(Math.round(ratio.used_ratio * 100), ratio.reset_time);
170
+ } else {
171
+ const detail = kimiSessionDetail(data.limits);
172
+ const used = parseKimiCount(detail?.used);
173
+ const limit = parseKimiCount(detail?.limit);
174
+ if (used !== undefined && limit !== undefined && limit > 0) {
175
+ cacheKimiSession(Math.round((used / limit) * 100), detail?.resetTime);
176
+ }
177
+ }
178
+
179
+ const parts = [
180
+ renderKimiSession(),
181
+ formatKimiRatioWindow("wk", data.usages?.limit_7d) ?? formatKimiWindow("wk", data.usage),
182
+ ].filter((part): part is string => part !== undefined);
183
+ return parts.length > 0 ? parts.join(" · ") : undefined;
184
+ },
185
+ };
186
+
187
+ interface CodexUsageWindow {
188
+ used_percent?: number;
189
+ limit_window_seconds?: number;
190
+ reset_after_seconds?: number;
191
+ reset_at?: number;
192
+ }
193
+
194
+ interface CodexUsageResponse {
195
+ rate_limit?: {
196
+ primary_window?: CodexUsageWindow | null;
197
+ secondary_window?: CodexUsageWindow | null;
198
+ };
199
+ }
200
+
201
+ function codexWindowLabel(seconds?: number): string {
202
+ if (seconds == null) return "limit";
203
+ if (seconds >= 6 * 24 * 60 * 60) return "wk";
204
+ if (seconds >= 20 * 60 * 60 && seconds <= 28 * 60 * 60) return "day";
205
+ if (seconds >= 4 * 60 * 60 && seconds <= 6 * 60 * 60) return "5h";
206
+ const hours = Math.round(seconds / 3600);
207
+ return hours >= 24 && hours % 24 === 0 ? `${hours / 24}d` : `${hours}h`;
208
+ }
209
+
210
+ function progressBar(percent: number, width = 8): string {
211
+ const clamped = Math.max(0, Math.min(100, percent));
212
+ const filled = Math.round((clamped / 100) * width);
213
+ return `[${"█".repeat(filled)}${"░".repeat(width - filled)}]`;
214
+ }
215
+
216
+ function formatCodexWindow(window: CodexUsageWindow | null | undefined): string | undefined {
217
+ if (typeof window?.used_percent !== "number") return undefined;
218
+ const reset = typeof window.reset_after_seconds === "number"
219
+ ? fmtDuration(window.reset_after_seconds * 1000)
220
+ : typeof window.reset_at === "number"
221
+ ? fmtDuration(window.reset_at * 1000 - Date.now())
222
+ : "?";
223
+ const percent = Math.round(window.used_percent);
224
+ return `${codexWindowLabel(window.limit_window_seconds)} ${progressBar(percent)} ${percent}% ↻${reset}`;
225
+ }
226
+
227
+ function codexAccountId(token: string): string | undefined {
228
+ try {
229
+ const payload = token.split(".")[1];
230
+ if (!payload) return undefined;
231
+ const claims = JSON.parse(Buffer.from(payload, "base64url").toString("utf8")) as {
232
+ "https://api.openai.com/auth"?: { chatgpt_account_id?: string };
233
+ };
234
+ const accountId = claims["https://api.openai.com/auth"]?.chatgpt_account_id;
235
+ return typeof accountId === "string" && accountId ? accountId : undefined;
236
+ } catch {
237
+ return undefined;
238
+ }
239
+ }
240
+
241
+ const openaiCodex: UsageProvider = {
242
+ providerId: "openai-codex",
243
+ label: "codex",
244
+ matches: (provider) => provider === "openai-codex",
245
+ async fetch(ctx) {
246
+ const result = await ctx.modelRegistry.getProviderAuth("openai-codex");
247
+ const token = result?.auth?.apiKey;
248
+ const accountId = token ? codexAccountId(token) : undefined;
249
+ if (!token || !accountId) return undefined;
250
+
251
+ const base = (result.auth.baseUrl ?? "https://chatgpt.com/backend-api").replace(/\/+$/, "");
252
+ const res = await fetch(`${base}/wham/usage`, {
253
+ headers: {
254
+ ...result.auth.headers,
255
+ Authorization: `Bearer ${token}`,
256
+ "chatgpt-account-id": accountId,
257
+ originator: "pi",
258
+ "User-Agent": "pi",
259
+ },
260
+ });
261
+ if (!res.ok) return undefined;
262
+
263
+ const data = (await res.json()) as CodexUsageResponse;
264
+ const parts = [
265
+ formatCodexWindow(data.rate_limit?.primary_window),
266
+ formatCodexWindow(data.rate_limit?.secondary_window),
267
+ ].filter((part): part is string => part !== undefined);
268
+ return parts.length > 0 ? parts.join(" · ") : undefined;
269
+ },
270
+ };
271
+
272
+ interface ClaudeCodeCredentials {
273
+ claudeAiOauth?: {
274
+ accessToken?: string;
275
+ refreshToken?: string;
276
+ expiresAt?: number;
277
+ scopes?: string[];
278
+ };
279
+ }
280
+
281
+ interface ClaudeUsageWindow {
282
+ utilization?: number;
283
+ resets_at?: string | null;
284
+ }
285
+
286
+ interface ClaudeUsageResponse {
287
+ five_hour?: ClaudeUsageWindow | null;
288
+ seven_day?: ClaudeUsageWindow | null;
289
+ seven_day_opus?: ClaudeUsageWindow | null;
290
+ seven_day_sonnet?: ClaudeUsageWindow | null;
291
+ extra_usage?: {
292
+ is_enabled?: boolean;
293
+ used_credits?: number | null;
294
+ monthly_limit?: number | null;
295
+ currency?: string | null;
296
+ };
297
+ }
298
+
299
+ const CLAUDE_USAGE_URL = "https://api.anthropic.com/api/oauth/usage";
300
+ const CLAUDE_CACHE_MS = 5 * 60_000;
301
+ let claudeUsageCache: { fetchedAt: number; data: ClaudeUsageResponse } | undefined;
302
+
303
+ const CLAUDE_TOKEN_URL = "https://platform.claude.com/v1/oauth/token";
304
+ const CLAUDE_CLIENT_ID = "9d1c250a-e61b-44d9-88ed-5944d1962f5e";
305
+ const CLAUDE_USER_AGENT = "claude-cli/2.1.292 (external, cli)";
306
+ // Renew this early so a token never expires mid-request.
307
+ const CLAUDE_REFRESH_SKEW_MS = 5 * 60_000;
308
+
309
+ function claudeCredentialsPath(): string {
310
+ const configDir = process.env.CLAUDE_CONFIG_DIR ?? join(homedir(), ".claude");
311
+ return join(configDir, ".credentials.json");
312
+ }
313
+
314
+ async function readClaudeCredentials(): Promise<ClaudeCodeCredentials | undefined> {
315
+ try {
316
+ return JSON.parse(await readFile(claudeCredentialsPath(), "utf8")) as ClaudeCodeCredentials;
317
+ } catch {
318
+ return undefined;
319
+ }
320
+ }
321
+
322
+ async function refreshClaudeAccessToken(credentials: ClaudeCodeCredentials): Promise<string | undefined> {
323
+ const oauth = credentials.claudeAiOauth;
324
+ if (!oauth?.refreshToken) return undefined;
325
+ try {
326
+ const res = await fetch(CLAUDE_TOKEN_URL, {
327
+ method: "POST",
328
+ headers: {
329
+ "Content-Type": "application/json",
330
+ Accept: "application/json",
331
+ "User-Agent": CLAUDE_USER_AGENT,
332
+ },
333
+ body: JSON.stringify({
334
+ grant_type: "refresh_token",
335
+ refresh_token: oauth.refreshToken,
336
+ client_id: CLAUDE_CLIENT_ID,
337
+ ...(oauth.scopes?.length ? { scope: oauth.scopes.join(" ") } : {}),
338
+ }),
339
+ });
340
+ if (!res.ok) return undefined;
341
+ const data = (await res.json()) as { access_token?: string; refresh_token?: string; expires_in?: number };
342
+ if (typeof data.access_token !== "string" || typeof data.refresh_token !== "string") return undefined;
343
+ if (typeof data.expires_in !== "number") return undefined;
344
+
345
+ // Refresh tokens rotate, so persist the new pair like Claude Code does.
346
+ credentials.claudeAiOauth = {
347
+ ...oauth,
348
+ accessToken: data.access_token,
349
+ refreshToken: data.refresh_token,
350
+ expiresAt: Date.now() + data.expires_in * 1000,
351
+ };
352
+ await writeFile(claudeCredentialsPath(), JSON.stringify(credentials), { mode: 0o600 });
353
+ return data.access_token;
354
+ } catch {
355
+ return undefined;
356
+ }
357
+ }
358
+
359
+ // Serialize renewals so concurrent fetches share one in-flight refresh.
360
+ let claudeRefresh: Promise<string | undefined> | undefined;
361
+
362
+ async function loadClaudeAccessToken(): Promise<string | undefined> {
363
+ if (process.env.CLAUDE_CODE_OAUTH_TOKEN) return process.env.CLAUDE_CODE_OAUTH_TOKEN;
364
+ const credentials = await readClaudeCredentials();
365
+ if (!credentials?.claudeAiOauth?.accessToken) return undefined;
366
+ const oauth = credentials.claudeAiOauth;
367
+ if (typeof oauth.expiresAt !== "number" || oauth.expiresAt - Date.now() > CLAUDE_REFRESH_SKEW_MS) {
368
+ return oauth.accessToken;
369
+ }
370
+ // Access tokens live ~8h. Renew expired ones here instead of failing until
371
+ // Claude Code happens to run and refresh them.
372
+ claudeRefresh ??= refreshClaudeAccessToken(credentials).finally(() => {
373
+ claudeRefresh = undefined;
374
+ });
375
+ return claudeRefresh;
376
+ }
377
+
378
+ function formatClaudeWindow(label: string, window: ClaudeUsageWindow | null | undefined): string | undefined {
379
+ if (typeof window?.utilization !== "number") return undefined;
380
+ const percent = Math.round(window.utilization);
381
+ const reset = window.resets_at ? fmtCountdown(window.resets_at) : "?";
382
+ return `${label} ${progressBar(percent)} ${percent}% ↻${reset}`;
383
+ }
384
+
385
+ function formatClaudeUsage(data: ClaudeUsageResponse): string | undefined {
386
+ const parts = [
387
+ formatClaudeWindow("5h", data.five_hour),
388
+ formatClaudeWindow("wk", data.seven_day),
389
+ formatClaudeWindow("opus", data.seven_day_opus),
390
+ formatClaudeWindow("sonnet", data.seven_day_sonnet),
391
+ ].filter((part): part is string => part !== undefined);
392
+
393
+ if (data.extra_usage?.is_enabled) {
394
+ const used = data.extra_usage.used_credits;
395
+ const limit = data.extra_usage.monthly_limit;
396
+ const currency = data.extra_usage.currency ?? "USD";
397
+ parts.push(
398
+ typeof used === "number" && typeof limit === "number"
399
+ ? `extra ${used.toFixed(2)}/${limit.toFixed(2)} ${currency}`
400
+ : "extra enabled",
401
+ );
402
+ }
403
+ return parts.length > 0 ? parts.join(" · ") : undefined;
404
+ }
405
+
406
+ const claudeCodeBridge: UsageProvider = {
407
+ // Claude Code owns authentication; claude-bridge does not expose it through
408
+ // pi's model registry.
409
+ providerId: "claude-bridge",
410
+ label: "claude",
411
+ matches: (provider) => provider === "claude-bridge",
412
+ async connected() {
413
+ return Boolean(await loadClaudeAccessToken());
414
+ },
415
+ async fetch() {
416
+ if (claudeUsageCache && Date.now() - claudeUsageCache.fetchedAt < CLAUDE_CACHE_MS) {
417
+ return formatClaudeUsage(claudeUsageCache.data);
418
+ }
419
+
420
+ const token = await loadClaudeAccessToken();
421
+ if (!token) return undefined;
422
+ const res = await fetch(CLAUDE_USAGE_URL, {
423
+ headers: {
424
+ Accept: "application/json",
425
+ Authorization: `Bearer ${token}`,
426
+ "anthropic-beta": "oauth-2025-04-20",
427
+ "User-Agent": "claude-code/usage-extension",
428
+ },
429
+ });
430
+ if (!res.ok) return claudeUsageCache ? formatClaudeUsage(claudeUsageCache.data) : undefined;
431
+
432
+ const data = (await res.json()) as ClaudeUsageResponse;
433
+ claudeUsageCache = { fetchedAt: Date.now(), data };
434
+ return formatClaudeUsage(data);
435
+ },
436
+ };
437
+
438
+ interface ZenDashboardConfig {
439
+ workspaceId: string;
440
+ authCookie: string;
441
+ serverId?: string;
442
+ serverInstance?: string;
443
+ }
444
+
445
+ interface ZenCreditsResponse {
446
+ data?: {
447
+ total_credits?: number;
448
+ used_credits?: number;
449
+ remaining_credits?: number;
450
+ };
451
+ }
452
+
453
+ const ZEN_CONFIG_PATH = join(getAgentDir(), "usage-zen.json");
454
+ const ZEN_SERVER_ID = "c83b78a614689c38ebee981f9b39a8b377716db85c1fd7dbab604adc02d3313d";
455
+ const ZEN_SERVER_INSTANCE = "server-fn:2";
456
+ const ZEN_USER_AGENT =
457
+ "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/151.0.0.0 Safari/537.36";
458
+ let zenCreditsApiSupported: boolean | undefined;
459
+
460
+ async function loadZenConfig(): Promise<ZenDashboardConfig | undefined> {
461
+ const envWorkspace = process.env.OPENCODE_ZEN_WORKSPACE_ID;
462
+ const envCookie = process.env.OPENCODE_ZEN_AUTH_COOKIE;
463
+ if (envWorkspace && envCookie) return { workspaceId: envWorkspace, authCookie: envCookie };
464
+ try {
465
+ const config = JSON.parse(await readFile(ZEN_CONFIG_PATH, "utf8")) as Partial<ZenDashboardConfig>;
466
+ if (typeof config.workspaceId !== "string" || typeof config.authCookie !== "string") return undefined;
467
+ return config as ZenDashboardConfig;
468
+ } catch {
469
+ return undefined;
470
+ }
471
+ }
472
+
473
+ function zenCookieHeader(cookie: string): string {
474
+ return cookie.trim().startsWith("auth=") ? cookie.trim() : `auth=${cookie.trim()}`;
475
+ }
476
+
477
+ function microCentsToDollars(value: number): number {
478
+ return value / 100_000_000;
479
+ }
480
+
481
+ function parseZenDashboardResponse(body: string): string | undefined {
482
+ const balance = body.match(/\bbalance:\s*(-?\d+)/)?.[1];
483
+ if (balance == null) return undefined;
484
+ const parts = [`balance $${microCentsToDollars(Number(balance)).toFixed(2)}`];
485
+ const monthlyUsage = body.match(/\bmonthlyUsage:\s*(-?\d+)/)?.[1];
486
+ if (monthlyUsage != null) parts.push(`mo $${microCentsToDollars(Number(monthlyUsage)).toFixed(2)}`);
487
+ const reload = body.match(/\breload:\s*(true|false|null)/)?.[1];
488
+ const reloadAmount = body.match(/\breloadAmount:\s*(\d+(?:\.\d+)?)/)?.[1];
489
+ const reloadTrigger = body.match(/\breloadTrigger:\s*(\d+(?:\.\d+)?)/)?.[1];
490
+ if (reload === "true" && reloadAmount && reloadTrigger) {
491
+ parts.push(`auto $${reloadAmount} @ $${reloadTrigger}`);
492
+ }
493
+ return parts.join(" · ");
494
+ }
495
+
496
+ async function fetchZenDashboard(config: ZenDashboardConfig): Promise<string | undefined> {
497
+ const serverId = config.serverId ?? ZEN_SERVER_ID;
498
+ const serverInstance = config.serverInstance ?? ZEN_SERVER_INSTANCE;
499
+ const args = JSON.stringify({
500
+ t: { t: 9, i: 0, l: 1, a: [{ t: 1, s: config.workspaceId }], o: 0 },
501
+ f: 31,
502
+ m: [],
503
+ });
504
+ const headers = {
505
+ Accept: "*/*",
506
+ Cookie: zenCookieHeader(config.authCookie),
507
+ Referer: `https://opencode.ai/workspace/${config.workspaceId}`,
508
+ "User-Agent": ZEN_USER_AGENT,
509
+ "x-server-id": serverId,
510
+ "x-server-instance": serverInstance,
511
+ };
512
+
513
+ const endpoint = new URL("https://opencode.ai/_server");
514
+ endpoint.searchParams.set("id", serverId);
515
+ endpoint.searchParams.set("args", args);
516
+ const direct = await fetch(endpoint, { headers });
517
+ if (direct.ok) {
518
+ const usage = parseZenDashboardResponse(await direct.text());
519
+ if (usage) return usage;
520
+ }
521
+
522
+ // The server-function hash can change after a Zen deployment. The workspace
523
+ // page is slower but exposes the same billing object in its SSR hydration.
524
+ const page = await fetch(`https://opencode.ai/workspace/${encodeURIComponent(config.workspaceId)}`, {
525
+ headers: {
526
+ Accept: "text/html",
527
+ Cookie: zenCookieHeader(config.authCookie),
528
+ "User-Agent": ZEN_USER_AGENT,
529
+ },
530
+ });
531
+ return page.ok ? parseZenDashboardResponse(await page.text()) : undefined;
532
+ }
533
+
534
+ async function fetchZenCreditsApi(ctx: ExtensionContext): Promise<string | undefined> {
535
+ if (zenCreditsApiSupported === false) return undefined;
536
+ const result = await ctx.modelRegistry.getProviderAuth("opencode");
537
+ const apiKey = result?.auth?.apiKey;
538
+ if (!apiKey) return undefined;
539
+ const res = await fetch("https://api.opencode.ai/v1/credits", {
540
+ headers: { Accept: "application/json", Authorization: `Bearer ${apiKey}` },
541
+ });
542
+ if (!res.ok) return undefined;
543
+ if (!(res.headers.get("content-type") ?? "").toLowerCase().includes("json")) {
544
+ zenCreditsApiSupported = false;
545
+ return undefined;
546
+ }
547
+ zenCreditsApiSupported = true;
548
+ const data = ((await res.json()) as ZenCreditsResponse).data;
549
+ if (typeof data?.total_credits !== "number" || typeof data.used_credits !== "number") return undefined;
550
+ const total = data.total_credits;
551
+ const used = data.used_credits;
552
+ const remaining = typeof data.remaining_credits === "number" ? data.remaining_credits : total - used;
553
+ const percent = total > 0 ? Math.round((used / total) * 100) : 0;
554
+ return `${remaining.toFixed(2)}/${total.toFixed(2)} credits · ${percent}% used`;
555
+ }
556
+
557
+ const openCodeZen: UsageProvider = {
558
+ providerId: "opencode",
559
+ label: "zen",
560
+ matches: (provider) => provider === "opencode",
561
+ async connected(ctx) {
562
+ if (await loadZenConfig()) return true;
563
+ const result = await ctx.modelRegistry.getProviderAuth("opencode");
564
+ return Boolean(result?.auth?.apiKey);
565
+ },
566
+ async fetch(ctx) {
567
+ const official = await fetchZenCreditsApi(ctx);
568
+ if (official) return official;
569
+ const config = await loadZenConfig();
570
+ return config ? fetchZenDashboard(config) : undefined;
571
+ },
572
+ };
573
+
574
+ // Add more provider handlers here later.
575
+ const USAGE_PROVIDERS: UsageProvider[] = [kimiCoding, openaiCodex, claudeCodeBridge, openCodeZen];
576
+
577
+ // ---------------------------------------------------------------------------
578
+ // Extension
579
+ // ---------------------------------------------------------------------------
580
+
581
+ export default function (pi: ExtensionAPI) {
582
+ let timer: ReturnType<typeof setInterval> | undefined;
583
+ let visible = false;
584
+ const succeededProviders = new Set<string>();
585
+
586
+ function handlerFor(ctx: ExtensionContext): UsageProvider | undefined {
587
+ const provider = ctx.model?.provider;
588
+ if (!provider) return undefined;
589
+ return USAGE_PROVIDERS.find((p) => p.matches(provider));
590
+ }
591
+
592
+ async function refresh(ctx: ExtensionContext): Promise<void> {
593
+ if (!ctx.hasUI) return;
594
+
595
+ const handler = handlerFor(ctx);
596
+ if (!handler) {
597
+ if (visible) {
598
+ ctx.ui.setWidget(STATUS_ID, undefined, { placement: "belowEditor" });
599
+ visible = false;
600
+ }
601
+ return;
602
+ }
603
+
604
+ try {
605
+ const text = await handler.fetch(ctx);
606
+ const model = ctx.model?.id ?? "";
607
+ const provider = ctx.model?.provider ?? "";
608
+ if (text) {
609
+ ctx.ui.setWidget(STATUS_ID, [ctx.ui.theme.fg("dim", `${handler.label} ${model} · ${text}`)], {
610
+ placement: "belowEditor",
611
+ });
612
+ succeededProviders.add(provider);
613
+ } else if (!succeededProviders.has(provider)) {
614
+ // Never fetched successfully for this provider: show that the extension is alive.
615
+ ctx.ui.setWidget(STATUS_ID, [ctx.ui.theme.fg("dim", `${handler.label} ${model} · usage n/a`)], {
616
+ placement: "belowEditor",
617
+ });
618
+ }
619
+ // On later failures: keep the last known values on screen.
620
+ visible = true;
621
+ } catch {
622
+ // Network/auth errors: keep the last known values on screen.
623
+ }
624
+ }
625
+
626
+ pi.on("session_start", async (_event, ctx) => {
627
+ await refresh(ctx);
628
+ // Keep values and renewal countdowns fresh.
629
+ timer = setInterval(() => {
630
+ void refresh(ctx);
631
+ }, REFRESH_MS);
632
+ });
633
+
634
+ pi.on("session_shutdown", async () => {
635
+ if (timer) {
636
+ clearInterval(timer);
637
+ timer = undefined;
638
+ }
639
+ });
640
+
641
+ // Refresh after every prompt completes.
642
+ pi.on("agent_settled", async (_event, ctx) => {
643
+ await refresh(ctx);
644
+ });
645
+
646
+ // Show/hide when the active model changes.
647
+ pi.on("model_select", async (_event, ctx) => {
648
+ await refresh(ctx);
649
+ });
650
+
651
+ // Manual refresh: /usage
652
+ pi.registerCommand("usage", {
653
+ description: "Refresh the usage display below the editor",
654
+ handler: async (_args, ctx) => {
655
+ await refresh(ctx);
656
+ ctx.ui.notify("Usage refreshed", "info");
657
+ },
658
+ });
659
+
660
+ pi.registerCommand("usage-all", {
661
+ description: "Show credits for all connected plans",
662
+ handler: async (_args, ctx) => {
663
+ const results = await Promise.all(
664
+ USAGE_PROVIDERS.map(async (handler) => {
665
+ try {
666
+ if (!(await isConnected(handler, ctx))) return undefined;
667
+ // Treat a failed fetch as not connected: expired cookies/tokens
668
+ // (e.g. a stale usage-zen.json after logout) must not produce output.
669
+ const usage = await handler.fetch(ctx);
670
+ return usage ? `${handler.label}: ${usage}` : undefined;
671
+ } catch {
672
+ return undefined;
673
+ }
674
+ }),
675
+ );
676
+ const connected = results.filter((result): result is string => result !== undefined);
677
+ if (connected.length === 0) {
678
+ ctx.ui.notify("No supported usage plans are connected", "warning");
679
+ return;
680
+ }
681
+ ctx.ui.notify(connected.join("\n"), "info");
682
+ },
683
+ });
684
+ }