pi-usage-lite 0.1.1 → 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 +28 -0
- package/README.md +51 -55
- package/package.json +11 -4
- package/src/index.ts +146 -20
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/README.md
CHANGED
|
@@ -1,14 +1,43 @@
|
|
|
1
1
|
# pi-usage-lite
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[](https://www.npmjs.com/package/pi-usage-lite)
|
|
4
|
+
[](https://www.npmjs.com/package/pi-usage-lite)
|
|
5
|
+
[](https://github.com/HossinAmin/pi-usage-lite/actions/workflows/ci.yml)
|
|
6
|
+
[](./LICENSE)
|
|
4
7
|
|
|
5
|
-
|
|
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.
|
|
6
9
|
|
|
7
|
-
|
|
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
|
+
```
|
|
8
37
|
|
|
9
38
|
## Features
|
|
10
39
|
|
|
11
|
-
- Shows usage in Pi's
|
|
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.
|
|
12
41
|
- Refreshes when a session starts, when the model changes, after each agent run, and every 60 seconds.
|
|
13
42
|
- Keeps the last known values visible when a later refresh fails.
|
|
14
43
|
- Provides `/usage` to refresh the active provider.
|
|
@@ -23,43 +52,24 @@ The extension is intentionally small: one TypeScript file, no runtime package de
|
|
|
23
52
|
| Claude Code Bridge | Five-hour, weekly, Opus, Sonnet, and extra-usage information when available |
|
|
24
53
|
| OpenCode Zen | Numeric credit balance and spending information |
|
|
25
54
|
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
Provider data is shown only when Pi has compatible credentials configured.
|
|
29
|
-
|
|
30
|
-
## Install
|
|
31
|
-
|
|
32
|
-
Install a GitHub release tag. Pinning a release prevents later changes on `main` or `dev` from affecting your installation unexpectedly:
|
|
33
|
-
|
|
34
|
-
```bash
|
|
35
|
-
pi install git:github.com/HossinAmin/pi-usage-lite@v0.1.1
|
|
36
|
-
```
|
|
37
|
-
|
|
38
|
-
Check [GitHub Releases](https://github.com/HossinAmin/pi-usage-lite/releases) for the newest tag, then restart Pi or run:
|
|
55
|
+
The row shows the active model's provider. Example rows for each provider:
|
|
39
56
|
|
|
40
57
|
```text
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
```bash
|
|
47
|
-
pi -e git:github.com/HossinAmin/pi-usage-lite@v0.1.1
|
|
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
|
|
48
62
|
```
|
|
49
63
|
|
|
50
|
-
|
|
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.
|
|
51
65
|
|
|
52
|
-
|
|
53
|
-
git clone git@github.com:HossinAmin/pi-usage-lite.git
|
|
54
|
-
cd pi-usage-lite
|
|
55
|
-
pi -e .
|
|
56
|
-
```
|
|
66
|
+
Provider data is shown only when Pi has compatible credentials configured.
|
|
57
67
|
|
|
58
68
|
## Commands
|
|
59
69
|
|
|
60
70
|
### `/usage`
|
|
61
71
|
|
|
62
|
-
Refreshes the
|
|
72
|
+
Refreshes the usage row for the currently selected model's provider.
|
|
63
73
|
|
|
64
74
|
### `/usage-all`
|
|
65
75
|
|
|
@@ -110,30 +120,11 @@ export OPENCODE_ZEN_AUTH_COOKIE="your-open-code-auth-cookie"
|
|
|
110
120
|
## Compatibility notes
|
|
111
121
|
|
|
112
122
|
- The extension registers `/usage`. Do not load it alongside another extension that registers the same command.
|
|
113
|
-
- Usage endpoints and response formats are provider-controlled and may change.
|
|
114
|
-
- The
|
|
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.
|
|
115
126
|
- This project is not affiliated with Pi, OpenAI, Anthropic, Moonshot AI, Kimi, or OpenCode.
|
|
116
127
|
|
|
117
|
-
## Release workflow
|
|
118
|
-
|
|
119
|
-
Development happens on the `dev` branch or feature branches. Releases are created from `main`.
|
|
120
|
-
|
|
121
|
-
1. Make changes on `dev` or a feature branch.
|
|
122
|
-
2. Bump `package.json` before opening a pull request into `main`:
|
|
123
|
-
|
|
124
|
-
```bash
|
|
125
|
-
bun pm pkg set version=0.1.2
|
|
126
|
-
```
|
|
127
|
-
|
|
128
|
-
Use the next appropriate semver version instead of `0.1.2`.
|
|
129
|
-
|
|
130
|
-
3. Merge the pull request into `main`.
|
|
131
|
-
4. The [`Release`](./.github/workflows/release.yml) workflow validates the version, creates the matching `vX.Y.Z` tag, and publishes a GitHub Release with generated notes.
|
|
132
|
-
|
|
133
|
-
The [`Version check`](./.github/workflows/version-check.yml) workflow blocks pull requests into `main` when `package.json` still has the base branch's version. This keeps every merge into `main` releasable.
|
|
134
|
-
|
|
135
|
-
Users should install release tags such as `@v0.1.1`, not the moving `main` or `dev` branches.
|
|
136
|
-
|
|
137
128
|
## Development
|
|
138
129
|
|
|
139
130
|
The extension source is [`src/index.ts`](./src/index.ts).
|
|
@@ -144,9 +135,12 @@ Useful local commands:
|
|
|
144
135
|
# Install development dependencies
|
|
145
136
|
bun install
|
|
146
137
|
|
|
147
|
-
# Typecheck the extension
|
|
138
|
+
# Typecheck the extension and tests
|
|
148
139
|
bun run typecheck
|
|
149
140
|
|
|
141
|
+
# Run the tests
|
|
142
|
+
bun run test
|
|
143
|
+
|
|
150
144
|
# Try the package locally
|
|
151
145
|
pi -e .
|
|
152
146
|
|
|
@@ -154,7 +148,9 @@ pi -e .
|
|
|
154
148
|
${EDITOR:-nano} src/index.ts
|
|
155
149
|
```
|
|
156
150
|
|
|
157
|
-
There is no build step for users; Pi loads the TypeScript source through Jiti. Development dependencies are used only for local typechecking and release validation.
|
|
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.
|
|
158
154
|
|
|
159
155
|
## License
|
|
160
156
|
|
package/package.json
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-usage-lite",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "A minimal Pi Coding Agent extension that
|
|
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
5
|
"type": "module",
|
|
6
|
+
"types": "./src/index.ts",
|
|
6
7
|
"license": "MIT",
|
|
7
8
|
"author": {
|
|
8
9
|
"name": "HossinAmin",
|
|
@@ -10,7 +11,7 @@
|
|
|
10
11
|
},
|
|
11
12
|
"repository": {
|
|
12
13
|
"type": "git",
|
|
13
|
-
"url": "
|
|
14
|
+
"url": "https://github.com/HossinAmin/pi-usage-lite.git"
|
|
14
15
|
},
|
|
15
16
|
"homepage": "https://github.com/HossinAmin/pi-usage-lite#readme",
|
|
16
17
|
"bugs": {
|
|
@@ -32,6 +33,7 @@
|
|
|
32
33
|
"files": [
|
|
33
34
|
"src",
|
|
34
35
|
"README.md",
|
|
36
|
+
"CHANGELOG.md",
|
|
35
37
|
"LICENSE"
|
|
36
38
|
],
|
|
37
39
|
"pi": {
|
|
@@ -39,16 +41,21 @@
|
|
|
39
41
|
"./src/index.ts"
|
|
40
42
|
]
|
|
41
43
|
},
|
|
44
|
+
"publishConfig": {
|
|
45
|
+
"access": "public"
|
|
46
|
+
},
|
|
42
47
|
"peerDependencies": {
|
|
43
48
|
"@earendil-works/pi-coding-agent": "*"
|
|
44
49
|
},
|
|
45
50
|
"devDependencies": {
|
|
46
51
|
"@earendil-works/pi-coding-agent": "1.0.4",
|
|
52
|
+
"@types/bun": "^1.4.5",
|
|
47
53
|
"@types/node": "^26.6.4",
|
|
48
54
|
"typescript": "^7.0.2"
|
|
49
55
|
},
|
|
50
56
|
"scripts": {
|
|
51
|
-
"typecheck": "tsc --noEmit"
|
|
57
|
+
"typecheck": "tsc --noEmit && tsc --noEmit -p tests",
|
|
58
|
+
"test": "bun test"
|
|
52
59
|
},
|
|
53
60
|
"packageManager": "bun@1.3.14"
|
|
54
61
|
}
|
package/src/index.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Usage Extension
|
|
3
3
|
*
|
|
4
|
-
* Shows provider usage/quota in the
|
|
4
|
+
* Shows provider usage/quota in a dedicated row below the editor. Currently supports Kimi for
|
|
5
5
|
* Coding (5-hour + weekly quotas), OpenAI Codex (its available rate-limit
|
|
6
6
|
* windows), Claude Code Bridge (Claude plan windows), and OpenCode Zen credits.
|
|
7
7
|
* The status only appears while the active
|
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
*/
|
|
15
15
|
|
|
16
16
|
import { Buffer } from "node:buffer";
|
|
17
|
-
import { readFile } from "node:fs/promises";
|
|
17
|
+
import { readFile, writeFile } from "node:fs/promises";
|
|
18
18
|
import { homedir } from "node:os";
|
|
19
19
|
import { join } from "node:path";
|
|
20
20
|
import { getAgentDir, type ExtensionAPI, type ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
@@ -48,7 +48,7 @@ function fmtCountdown(resetIso: string): string {
|
|
|
48
48
|
interface UsageProvider {
|
|
49
49
|
/** Provider id used to resolve authentication. */
|
|
50
50
|
providerId: string;
|
|
51
|
-
/** Short label shown in the
|
|
51
|
+
/** Short label shown in the usage row and command output. */
|
|
52
52
|
label: string;
|
|
53
53
|
/** Return true if this handler serves the given provider id. */
|
|
54
54
|
matches(provider: string): boolean;
|
|
@@ -72,12 +72,21 @@ interface KimiQuotaDetail {
|
|
|
72
72
|
resetTime?: string;
|
|
73
73
|
}
|
|
74
74
|
|
|
75
|
+
interface KimiRatioWindow {
|
|
76
|
+
used_ratio?: number;
|
|
77
|
+
reset_time?: string;
|
|
78
|
+
}
|
|
79
|
+
|
|
75
80
|
interface KimiUsagesResponse {
|
|
76
|
-
usage?: KimiQuotaDetail; // weekly quota
|
|
81
|
+
usage?: KimiQuotaDetail; // weekly quota (legacy shape)
|
|
77
82
|
limits?: Array<{
|
|
78
83
|
window?: { duration?: number; timeUnit?: string };
|
|
79
|
-
detail?: KimiQuotaDetail; // session (
|
|
84
|
+
detail?: KimiQuotaDetail; // session window (legacy shape, omitted while no window is active)
|
|
80
85
|
}>;
|
|
86
|
+
usages?: {
|
|
87
|
+
limit_5h?: KimiRatioWindow; // session (5-hour) window
|
|
88
|
+
limit_7d?: KimiRatioWindow; // weekly quota
|
|
89
|
+
};
|
|
81
90
|
}
|
|
82
91
|
|
|
83
92
|
function parseKimiCount(value: string | undefined): number | undefined {
|
|
@@ -94,6 +103,41 @@ function formatKimiWindow(label: string, detail: KimiQuotaDetail | undefined): s
|
|
|
94
103
|
return `${label} ${progressBar(percent)} ${percent}% ↻${fmtCountdown(detail?.resetTime ?? "")}`;
|
|
95
104
|
}
|
|
96
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
|
+
|
|
97
141
|
const kimiCoding: UsageProvider = {
|
|
98
142
|
providerId: "kimi-coding",
|
|
99
143
|
label: "kimi",
|
|
@@ -118,12 +162,23 @@ const kimiCoding: UsageProvider = {
|
|
|
118
162
|
if (!res.ok) return undefined;
|
|
119
163
|
|
|
120
164
|
const data = (await res.json()) as KimiUsagesResponse;
|
|
121
|
-
|
|
122
|
-
|
|
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
|
+
}
|
|
123
178
|
|
|
124
179
|
const parts = [
|
|
125
|
-
|
|
126
|
-
formatKimiWindow("wk",
|
|
180
|
+
renderKimiSession(),
|
|
181
|
+
formatKimiRatioWindow("wk", data.usages?.limit_7d) ?? formatKimiWindow("wk", data.usage),
|
|
127
182
|
].filter((part): part is string => part !== undefined);
|
|
128
183
|
return parts.length > 0 ? parts.join(" · ") : undefined;
|
|
129
184
|
},
|
|
@@ -215,7 +270,12 @@ const openaiCodex: UsageProvider = {
|
|
|
215
270
|
};
|
|
216
271
|
|
|
217
272
|
interface ClaudeCodeCredentials {
|
|
218
|
-
claudeAiOauth?: {
|
|
273
|
+
claudeAiOauth?: {
|
|
274
|
+
accessToken?: string;
|
|
275
|
+
refreshToken?: string;
|
|
276
|
+
expiresAt?: number;
|
|
277
|
+
scopes?: string[];
|
|
278
|
+
};
|
|
219
279
|
}
|
|
220
280
|
|
|
221
281
|
interface ClaudeUsageWindow {
|
|
@@ -240,21 +300,81 @@ const CLAUDE_USAGE_URL = "https://api.anthropic.com/api/oauth/usage";
|
|
|
240
300
|
const CLAUDE_CACHE_MS = 5 * 60_000;
|
|
241
301
|
let claudeUsageCache: { fetchedAt: number; data: ClaudeUsageResponse } | undefined;
|
|
242
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
|
+
|
|
243
309
|
function claudeCredentialsPath(): string {
|
|
244
310
|
const configDir = process.env.CLAUDE_CONFIG_DIR ?? join(homedir(), ".claude");
|
|
245
311
|
return join(configDir, ".credentials.json");
|
|
246
312
|
}
|
|
247
313
|
|
|
248
|
-
async function
|
|
249
|
-
if (process.env.CLAUDE_CODE_OAUTH_TOKEN) return process.env.CLAUDE_CODE_OAUTH_TOKEN;
|
|
314
|
+
async function readClaudeCredentials(): Promise<ClaudeCodeCredentials | undefined> {
|
|
250
315
|
try {
|
|
251
|
-
|
|
252
|
-
return credentials.claudeAiOauth?.accessToken;
|
|
316
|
+
return JSON.parse(await readFile(claudeCredentialsPath(), "utf8")) as ClaudeCodeCredentials;
|
|
253
317
|
} catch {
|
|
254
318
|
return undefined;
|
|
255
319
|
}
|
|
256
320
|
}
|
|
257
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
|
+
|
|
258
378
|
function formatClaudeWindow(label: string, window: ClaudeUsageWindow | null | undefined): string | undefined {
|
|
259
379
|
if (typeof window?.utilization !== "number") return undefined;
|
|
260
380
|
const percent = Math.round(window.utilization);
|
|
@@ -475,7 +595,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
475
595
|
const handler = handlerFor(ctx);
|
|
476
596
|
if (!handler) {
|
|
477
597
|
if (visible) {
|
|
478
|
-
ctx.ui.
|
|
598
|
+
ctx.ui.setWidget(STATUS_ID, undefined, { placement: "belowEditor" });
|
|
479
599
|
visible = false;
|
|
480
600
|
}
|
|
481
601
|
return;
|
|
@@ -486,11 +606,15 @@ export default function (pi: ExtensionAPI) {
|
|
|
486
606
|
const model = ctx.model?.id ?? "";
|
|
487
607
|
const provider = ctx.model?.provider ?? "";
|
|
488
608
|
if (text) {
|
|
489
|
-
ctx.ui.
|
|
609
|
+
ctx.ui.setWidget(STATUS_ID, [ctx.ui.theme.fg("dim", `${handler.label} ${model} · ${text}`)], {
|
|
610
|
+
placement: "belowEditor",
|
|
611
|
+
});
|
|
490
612
|
succeededProviders.add(provider);
|
|
491
613
|
} else if (!succeededProviders.has(provider)) {
|
|
492
614
|
// Never fetched successfully for this provider: show that the extension is alive.
|
|
493
|
-
ctx.ui.
|
|
615
|
+
ctx.ui.setWidget(STATUS_ID, [ctx.ui.theme.fg("dim", `${handler.label} ${model} · usage n/a`)], {
|
|
616
|
+
placement: "belowEditor",
|
|
617
|
+
});
|
|
494
618
|
}
|
|
495
619
|
// On later failures: keep the last known values on screen.
|
|
496
620
|
visible = true;
|
|
@@ -526,7 +650,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
526
650
|
|
|
527
651
|
// Manual refresh: /usage
|
|
528
652
|
pi.registerCommand("usage", {
|
|
529
|
-
description: "Refresh the usage display
|
|
653
|
+
description: "Refresh the usage display below the editor",
|
|
530
654
|
handler: async (_args, ctx) => {
|
|
531
655
|
await refresh(ctx);
|
|
532
656
|
ctx.ui.notify("Usage refreshed", "info");
|
|
@@ -540,10 +664,12 @@ export default function (pi: ExtensionAPI) {
|
|
|
540
664
|
USAGE_PROVIDERS.map(async (handler) => {
|
|
541
665
|
try {
|
|
542
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.
|
|
543
669
|
const usage = await handler.fetch(ctx);
|
|
544
|
-
return `${handler.label}: ${usage
|
|
670
|
+
return usage ? `${handler.label}: ${usage}` : undefined;
|
|
545
671
|
} catch {
|
|
546
|
-
return
|
|
672
|
+
return undefined;
|
|
547
673
|
}
|
|
548
674
|
}),
|
|
549
675
|
);
|