@kmiyh/pi-codex-plan-limits 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/LICENSE +21 -0
- package/README.md +68 -0
- package/package.json +47 -0
- package/src/codex-plan-limits.jpg +0 -0
- package/src/index.ts +542 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026
|
|
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
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
# @kmiyh/pi-codex-plan-limits
|
|
2
|
+
|
|
3
|
+
`@kmiyh/pi-codex-plan-limits` is a Pi extension that shows your **OpenAI Codex subscription limits** in Pi's footer.
|
|
4
|
+
|
|
5
|
+
It replaces the less useful subscription footer segment with:
|
|
6
|
+
|
|
7
|
+
- **5h** remaining limit
|
|
8
|
+
- **Weekly** remaining limit
|
|
9
|
+
- reset time for both windows
|
|
10
|
+
|
|
11
|
+

|
|
12
|
+
|
|
13
|
+
## Installation
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
pi install npm:@kmiyh/pi-codex-plan-limits
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
## What it does
|
|
20
|
+
|
|
21
|
+
When Pi is using:
|
|
22
|
+
|
|
23
|
+
- provider: `openai-codex`
|
|
24
|
+
- auth mode: **OAuth / subscription auth**
|
|
25
|
+
|
|
26
|
+
the extension modifies the footer and shows Codex plan limits.
|
|
27
|
+
|
|
28
|
+
If Pi is using any other model, or `openai-codex` without subscription auth, the extension disables itself and the **default Pi footer is restored**.
|
|
29
|
+
|
|
30
|
+
## How it works
|
|
31
|
+
|
|
32
|
+
The extension uses **Pi's own auth session** for `openai-codex` and fetches usage from OpenAI's backend:
|
|
33
|
+
|
|
34
|
+
```text
|
|
35
|
+
https://chatgpt.com/backend-api/wham/usage
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
It does **not** depend on a separate Codex CLI login and does **not** read `~/.codex/sessions`.
|
|
39
|
+
|
|
40
|
+
If a live refresh fails, it keeps the last successful snapshot fetched through Pi.
|
|
41
|
+
|
|
42
|
+
## Refresh behavior
|
|
43
|
+
|
|
44
|
+
The limits are refreshed:
|
|
45
|
+
|
|
46
|
+
- on session start
|
|
47
|
+
- when the model changes
|
|
48
|
+
- after turns finish
|
|
49
|
+
- every 60 seconds
|
|
50
|
+
|
|
51
|
+
Event-driven refreshes are throttled to avoid excessive requests.
|
|
52
|
+
|
|
53
|
+
## Local development
|
|
54
|
+
|
|
55
|
+
```bash
|
|
56
|
+
npm install
|
|
57
|
+
npm run typecheck
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
For testing:
|
|
61
|
+
|
|
62
|
+
```bash
|
|
63
|
+
pi -e ./src/index.ts
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
## License
|
|
67
|
+
|
|
68
|
+
MIT
|
package/package.json
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@kmiyh/pi-codex-plan-limits",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Pi extension that shows live Codex plan usage: remaining 5h and weekly limits, reset times, and cached fallback snapshots.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"keywords": [
|
|
7
|
+
"pi-package",
|
|
8
|
+
"pi-agent",
|
|
9
|
+
"pi-extension",
|
|
10
|
+
"codex",
|
|
11
|
+
"usage",
|
|
12
|
+
"limits"
|
|
13
|
+
],
|
|
14
|
+
"files": [
|
|
15
|
+
"src",
|
|
16
|
+
"README.md",
|
|
17
|
+
"LICENSE"
|
|
18
|
+
],
|
|
19
|
+
"scripts": {
|
|
20
|
+
"typecheck": "tsc --noEmit"
|
|
21
|
+
},
|
|
22
|
+
"peerDependencies": {
|
|
23
|
+
"@mariozechner/pi-coding-agent": "*"
|
|
24
|
+
},
|
|
25
|
+
"devDependencies": {
|
|
26
|
+
"@mariozechner/pi-coding-agent": "*",
|
|
27
|
+
"@types/node": "^24.5.2",
|
|
28
|
+
"typescript": "^5.9.2"
|
|
29
|
+
},
|
|
30
|
+
"pi": {
|
|
31
|
+
"extensions": [
|
|
32
|
+
"./src/index.ts"
|
|
33
|
+
]
|
|
34
|
+
},
|
|
35
|
+
"repository": {
|
|
36
|
+
"type": "git",
|
|
37
|
+
"url": "git+https://github.com/Kmiyh/pi-codex-plan-limits.git"
|
|
38
|
+
},
|
|
39
|
+
"homepage": "https://github.com/Kmiyh/pi-codex-plan-limits#readme",
|
|
40
|
+
"bugs": {
|
|
41
|
+
"url": "https://github.com/Kmiyh/pi-codex-plan-limits/issues"
|
|
42
|
+
},
|
|
43
|
+
"license": "MIT",
|
|
44
|
+
"publishConfig": {
|
|
45
|
+
"access": "public"
|
|
46
|
+
}
|
|
47
|
+
}
|
|
Binary file
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,542 @@
|
|
|
1
|
+
import type { ExtensionAPI, ExtensionContext } from "@mariozechner/pi-coding-agent";
|
|
2
|
+
import { truncateToWidth, visibleWidth } from "@mariozechner/pi-tui";
|
|
3
|
+
|
|
4
|
+
const POLL_INTERVAL_MS = 60_000;
|
|
5
|
+
const MIN_EVENT_REFRESH_MS = 15_000;
|
|
6
|
+
const STALE_THRESHOLD_MS = 15 * 60_000;
|
|
7
|
+
const OPENAI_CODEX_PROVIDER = "openai-codex";
|
|
8
|
+
const DEFAULT_CHATGPT_BASE_URL = "https://chatgpt.com/backend-api/";
|
|
9
|
+
|
|
10
|
+
type UsageWindow = {
|
|
11
|
+
label: string;
|
|
12
|
+
remainingPercent: number;
|
|
13
|
+
resetsAtMs?: number;
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
type LimitsSnapshot = {
|
|
17
|
+
source: "live" | "cached";
|
|
18
|
+
capturedAtMs: number;
|
|
19
|
+
planType?: string;
|
|
20
|
+
primary?: UsageWindow;
|
|
21
|
+
secondary?: UsageWindow;
|
|
22
|
+
stale: boolean;
|
|
23
|
+
error?: string;
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
type PiOpenAICodexOAuthCredential = {
|
|
27
|
+
type: "oauth";
|
|
28
|
+
access?: string;
|
|
29
|
+
refresh?: string;
|
|
30
|
+
expires?: number;
|
|
31
|
+
accountId?: string;
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
type UsagePayloadWindow = {
|
|
35
|
+
used_percent?: number;
|
|
36
|
+
limit_window_seconds?: number;
|
|
37
|
+
reset_at?: number;
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
type UsagePayload = {
|
|
41
|
+
plan_type?: string;
|
|
42
|
+
rate_limit?: {
|
|
43
|
+
primary_window?: UsagePayloadWindow | null;
|
|
44
|
+
secondary_window?: UsagePayloadWindow | null;
|
|
45
|
+
} | null;
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
export default function codexPlanLimitsExtension(pi: ExtensionAPI) {
|
|
49
|
+
let latestSnapshot: LimitsSnapshot | undefined;
|
|
50
|
+
let refreshInFlight: Promise<void> | undefined;
|
|
51
|
+
let pollTimer: ReturnType<typeof setInterval> | undefined;
|
|
52
|
+
let activeCtx: ExtensionContext | undefined;
|
|
53
|
+
let lastRefreshStartedAt = 0;
|
|
54
|
+
|
|
55
|
+
async function refresh(ctx: ExtensionContext, options?: { notify?: boolean; force?: boolean }): Promise<void> {
|
|
56
|
+
if (!shouldShowForModel(ctx)) {
|
|
57
|
+
clearFooter(ctx);
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const now = Date.now();
|
|
62
|
+
if (!options?.force && now - lastRefreshStartedAt < 2_000) {
|
|
63
|
+
return refreshInFlight;
|
|
64
|
+
}
|
|
65
|
+
if (refreshInFlight) {
|
|
66
|
+
return refreshInFlight;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
lastRefreshStartedAt = now;
|
|
70
|
+
refreshInFlight = (async () => {
|
|
71
|
+
try {
|
|
72
|
+
const snapshot = await loadBestSnapshot(ctx, latestSnapshot);
|
|
73
|
+
latestSnapshot = snapshot;
|
|
74
|
+
render(ctx);
|
|
75
|
+
if (options?.notify && ctx.hasUI) {
|
|
76
|
+
ctx.ui.notify(snapshotNotification(snapshot), snapshot.stale ? "warning" : "info");
|
|
77
|
+
}
|
|
78
|
+
} catch (error) {
|
|
79
|
+
const message = error instanceof Error ? error.message : "Unknown error";
|
|
80
|
+
latestSnapshot = latestSnapshot
|
|
81
|
+
? {
|
|
82
|
+
...latestSnapshot,
|
|
83
|
+
source: "cached",
|
|
84
|
+
stale: true,
|
|
85
|
+
error: message,
|
|
86
|
+
}
|
|
87
|
+
: {
|
|
88
|
+
source: "cached",
|
|
89
|
+
capturedAtMs: Date.now(),
|
|
90
|
+
stale: true,
|
|
91
|
+
error: message,
|
|
92
|
+
};
|
|
93
|
+
render(ctx);
|
|
94
|
+
if (options?.notify && ctx.hasUI) {
|
|
95
|
+
ctx.ui.notify(`Codex limits unavailable: ${message}`, "warning");
|
|
96
|
+
}
|
|
97
|
+
} finally {
|
|
98
|
+
refreshInFlight = undefined;
|
|
99
|
+
}
|
|
100
|
+
})();
|
|
101
|
+
|
|
102
|
+
return refreshInFlight;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function render(ctx: ExtensionContext): void {
|
|
106
|
+
activeCtx = ctx;
|
|
107
|
+
if (!shouldShowForModel(ctx)) {
|
|
108
|
+
clearFooter(ctx);
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
setFooter(ctx, latestSnapshot);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function setFooter(ctx: ExtensionContext, snapshot: LimitsSnapshot | undefined): void {
|
|
115
|
+
if (!ctx.hasUI) {
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
ctx.ui.setFooter((_tui, theme, footerData) => ({
|
|
119
|
+
invalidate() {},
|
|
120
|
+
render(width: number) {
|
|
121
|
+
return buildFooterLines(ctx, snapshot, width, theme, footerData, pi.getThinkingLevel());
|
|
122
|
+
},
|
|
123
|
+
}));
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function clearFooter(ctx: ExtensionContext): void {
|
|
127
|
+
if (!ctx.hasUI) {
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
130
|
+
ctx.ui.setFooter(undefined);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function snapshotNotification(snapshot: LimitsSnapshot): string {
|
|
134
|
+
const source = snapshot.source === "live" ? "live" : "cached";
|
|
135
|
+
const parts: string[] = [];
|
|
136
|
+
if (snapshot.primary) {
|
|
137
|
+
parts.push(`${snapshot.primary.label} ${formatPercent(snapshot.primary.remainingPercent)} left`);
|
|
138
|
+
}
|
|
139
|
+
if (snapshot.secondary) {
|
|
140
|
+
parts.push(`${snapshot.secondary.label} ${formatPercent(snapshot.secondary.remainingPercent)} left`);
|
|
141
|
+
}
|
|
142
|
+
return parts.length > 0
|
|
143
|
+
? `Codex limits refreshed (${source}): ${parts.join(" · ")}`
|
|
144
|
+
: `Codex limits refreshed (${source})`;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function startPolling(ctx: ExtensionContext): void {
|
|
148
|
+
stopPolling();
|
|
149
|
+
pollTimer = setInterval(() => {
|
|
150
|
+
void refresh(ctx);
|
|
151
|
+
}, POLL_INTERVAL_MS);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function stopPolling(): void {
|
|
155
|
+
if (pollTimer) {
|
|
156
|
+
clearInterval(pollTimer);
|
|
157
|
+
pollTimer = undefined;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
async function refreshIfDue(ctx: ExtensionContext): Promise<void> {
|
|
162
|
+
if (!shouldShowForModel(ctx)) {
|
|
163
|
+
clearFooter(ctx);
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
if (Date.now() - lastRefreshStartedAt < MIN_EVENT_REFRESH_MS) {
|
|
167
|
+
render(ctx);
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
await refresh(ctx);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
pi.on("session_start", async (_event, ctx) => {
|
|
174
|
+
activeCtx = ctx;
|
|
175
|
+
startPolling(ctx);
|
|
176
|
+
if (shouldShowForModel(ctx)) {
|
|
177
|
+
await refresh(ctx, { force: true });
|
|
178
|
+
} else {
|
|
179
|
+
clearFooter(ctx);
|
|
180
|
+
}
|
|
181
|
+
});
|
|
182
|
+
|
|
183
|
+
pi.on("model_select", async (_event, ctx) => {
|
|
184
|
+
activeCtx = ctx;
|
|
185
|
+
if (!shouldShowForModel(ctx)) {
|
|
186
|
+
clearFooter(ctx);
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
await refresh(ctx, { force: true });
|
|
190
|
+
});
|
|
191
|
+
|
|
192
|
+
pi.on("turn_end", async (_event, ctx) => {
|
|
193
|
+
activeCtx = ctx;
|
|
194
|
+
await refreshIfDue(ctx);
|
|
195
|
+
});
|
|
196
|
+
|
|
197
|
+
pi.on("session_shutdown", async () => {
|
|
198
|
+
stopPolling();
|
|
199
|
+
if (activeCtx?.hasUI) {
|
|
200
|
+
activeCtx.ui.setFooter(undefined);
|
|
201
|
+
}
|
|
202
|
+
activeCtx = undefined;
|
|
203
|
+
});
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
async function loadBestSnapshot(
|
|
207
|
+
ctx: ExtensionContext,
|
|
208
|
+
previousSnapshot: LimitsSnapshot | undefined,
|
|
209
|
+
): Promise<LimitsSnapshot> {
|
|
210
|
+
try {
|
|
211
|
+
return await fetchLiveSnapshotFromPiAuth(ctx);
|
|
212
|
+
} catch (error) {
|
|
213
|
+
if (!previousSnapshot) {
|
|
214
|
+
throw error;
|
|
215
|
+
}
|
|
216
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
217
|
+
return {
|
|
218
|
+
...previousSnapshot,
|
|
219
|
+
source: "cached",
|
|
220
|
+
stale: Date.now() - previousSnapshot.capturedAtMs > STALE_THRESHOLD_MS,
|
|
221
|
+
error: message,
|
|
222
|
+
};
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
async function fetchLiveSnapshotFromPiAuth(ctx: ExtensionContext): Promise<LimitsSnapshot> {
|
|
227
|
+
if (!ctx.model || ctx.model.provider !== OPENAI_CODEX_PROVIDER) {
|
|
228
|
+
throw new Error("Active Pi model is not an OpenAI Codex subscription model");
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
const authResult = await ctx.modelRegistry.getApiKeyAndHeaders(ctx.model);
|
|
232
|
+
if (!authResult.ok) {
|
|
233
|
+
throw new Error(authResult.error);
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
const credential = ctx.modelRegistry.authStorage.get(OPENAI_CODEX_PROVIDER) as PiOpenAICodexOAuthCredential | undefined;
|
|
237
|
+
const accessToken = credential?.access;
|
|
238
|
+
const accountId = credential?.accountId;
|
|
239
|
+
if (!accessToken || !accountId) {
|
|
240
|
+
throw new Error("Missing Pi OpenAI Codex OAuth credentials. Run /login and select OpenAI Codex.");
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
const baseUrl = ensureTrailingSlash(process.env.PI_CODEX_CHATGPT_BASE_URL ?? DEFAULT_CHATGPT_BASE_URL);
|
|
244
|
+
const usageUrl = new URL("wham/usage", baseUrl).toString();
|
|
245
|
+
const response = await fetch(usageUrl, {
|
|
246
|
+
method: "GET",
|
|
247
|
+
headers: {
|
|
248
|
+
Authorization: `Bearer ${accessToken}`,
|
|
249
|
+
"chatgpt-account-id": accountId,
|
|
250
|
+
"Content-Type": "application/json",
|
|
251
|
+
},
|
|
252
|
+
signal: AbortSignal.timeout(15_000),
|
|
253
|
+
});
|
|
254
|
+
|
|
255
|
+
if (!response.ok) {
|
|
256
|
+
const body = await safeReadText(response);
|
|
257
|
+
throw new Error(`Usage request failed (${response.status}): ${truncateInline(body, 200)}`);
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
const payload = (await response.json()) as UsagePayload;
|
|
261
|
+
const snapshot: LimitsSnapshot = {
|
|
262
|
+
source: "live",
|
|
263
|
+
capturedAtMs: Date.now(),
|
|
264
|
+
planType: normalizePlanType(payload.plan_type),
|
|
265
|
+
primary: mapWindow(payload.rate_limit?.primary_window, "5h"),
|
|
266
|
+
secondary: mapWindow(payload.rate_limit?.secondary_window, "Weekly"),
|
|
267
|
+
stale: false,
|
|
268
|
+
};
|
|
269
|
+
|
|
270
|
+
if (!snapshot.primary && !snapshot.secondary) {
|
|
271
|
+
throw new Error("Usage response did not contain 5h/weekly windows");
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
return snapshot;
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
function shouldShowForModel(ctx: ExtensionContext): boolean {
|
|
278
|
+
return Boolean(ctx.hasUI && ctx.model?.provider === OPENAI_CODEX_PROVIDER && ctx.modelRegistry.isUsingOAuth(ctx.model));
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
function mapWindow(window: UsagePayloadWindow | null | undefined, fallbackLabel: string): UsageWindow | undefined {
|
|
282
|
+
if (!window) {
|
|
283
|
+
return undefined;
|
|
284
|
+
}
|
|
285
|
+
const usedPercent = sanitizeNumber(window.used_percent);
|
|
286
|
+
const resetsAtMs = secondsToMs(window.reset_at);
|
|
287
|
+
const windowMinutes = secondsToMinutes(window.limit_window_seconds);
|
|
288
|
+
if (usedPercent === undefined && resetsAtMs === undefined && windowMinutes === undefined) {
|
|
289
|
+
return undefined;
|
|
290
|
+
}
|
|
291
|
+
const remainingPercent = clamp(100 - (usedPercent ?? 0), 0, 100);
|
|
292
|
+
return {
|
|
293
|
+
label: labelForWindow(windowMinutes, fallbackLabel),
|
|
294
|
+
remainingPercent,
|
|
295
|
+
resetsAtMs,
|
|
296
|
+
};
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
function buildFooterLines(
|
|
300
|
+
ctx: ExtensionContext,
|
|
301
|
+
snapshot: LimitsSnapshot | undefined,
|
|
302
|
+
width: number,
|
|
303
|
+
theme: ExtensionContext["ui"]["theme"],
|
|
304
|
+
footerData: {
|
|
305
|
+
getGitBranch(): string | null;
|
|
306
|
+
getExtensionStatuses(): ReadonlyMap<string, string>;
|
|
307
|
+
getAvailableProviderCount(): number;
|
|
308
|
+
},
|
|
309
|
+
thinkingLevel: string,
|
|
310
|
+
): string[] {
|
|
311
|
+
let pwd = ctx.cwd;
|
|
312
|
+
const home = process.env.HOME || process.env.USERPROFILE;
|
|
313
|
+
if (home && pwd.startsWith(home)) {
|
|
314
|
+
pwd = `~${pwd.slice(home.length)}`;
|
|
315
|
+
}
|
|
316
|
+
const branch = footerData.getGitBranch() ?? undefined;
|
|
317
|
+
if (branch) {
|
|
318
|
+
pwd = `${pwd} (${branch})`;
|
|
319
|
+
}
|
|
320
|
+
const sessionName = ctx.sessionManager.getSessionName();
|
|
321
|
+
if (sessionName) {
|
|
322
|
+
pwd = `${pwd} • ${sessionName}`;
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
let totalInput = 0;
|
|
326
|
+
let totalOutput = 0;
|
|
327
|
+
let totalCacheRead = 0;
|
|
328
|
+
let totalCacheWrite = 0;
|
|
329
|
+
for (const entry of ctx.sessionManager.getEntries()) {
|
|
330
|
+
if (entry.type === "message" && entry.message.role === "assistant") {
|
|
331
|
+
totalInput += entry.message.usage.input;
|
|
332
|
+
totalOutput += entry.message.usage.output;
|
|
333
|
+
totalCacheRead += entry.message.usage.cacheRead;
|
|
334
|
+
totalCacheWrite += entry.message.usage.cacheWrite;
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
const statsParts: string[] = [];
|
|
339
|
+
if (totalInput) statsParts.push(`↑${formatTokenCount(totalInput)}`);
|
|
340
|
+
if (totalOutput) statsParts.push(`↓${formatTokenCount(totalOutput)}`);
|
|
341
|
+
if (totalCacheRead) statsParts.push(`R${formatTokenCount(totalCacheRead)}`);
|
|
342
|
+
if (totalCacheWrite) statsParts.push(`W${formatTokenCount(totalCacheWrite)}`);
|
|
343
|
+
statsParts.push(buildLimitsText(snapshot, width));
|
|
344
|
+
let leftStats = statsParts.join(" ");
|
|
345
|
+
let leftStatsWidth = visibleWidth(leftStats);
|
|
346
|
+
if (leftStatsWidth > width) {
|
|
347
|
+
leftStats = truncateToWidth(leftStats, width, "...");
|
|
348
|
+
leftStatsWidth = visibleWidth(leftStats);
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
const modelName = ctx.model?.id || "no-model";
|
|
352
|
+
let rightSideWithoutProvider = modelName;
|
|
353
|
+
if (ctx.model?.reasoning) {
|
|
354
|
+
rightSideWithoutProvider = thinkingLevel === "off" ? `${modelName} • thinking off` : `${modelName} • ${thinkingLevel}`;
|
|
355
|
+
}
|
|
356
|
+
let rightSide = rightSideWithoutProvider;
|
|
357
|
+
if (footerData.getAvailableProviderCount() > 1 && ctx.model) {
|
|
358
|
+
rightSide = `(${ctx.model.provider}) ${rightSideWithoutProvider}`;
|
|
359
|
+
if (leftStatsWidth + 2 + visibleWidth(rightSide) > width) {
|
|
360
|
+
rightSide = rightSideWithoutProvider;
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
const rightSideWidth = visibleWidth(rightSide);
|
|
364
|
+
const totalNeeded = leftStatsWidth + 2 + rightSideWidth;
|
|
365
|
+
let statsLine: string;
|
|
366
|
+
if (totalNeeded <= width) {
|
|
367
|
+
const padding = " ".repeat(width - leftStatsWidth - rightSideWidth);
|
|
368
|
+
statsLine = leftStats + padding + rightSide;
|
|
369
|
+
} else {
|
|
370
|
+
const availableForRight = width - leftStatsWidth - 2;
|
|
371
|
+
if (availableForRight > 0) {
|
|
372
|
+
const truncatedRight = truncateToWidth(rightSide, availableForRight, "");
|
|
373
|
+
const truncatedRightWidth = visibleWidth(truncatedRight);
|
|
374
|
+
const padding = " ".repeat(Math.max(0, width - leftStatsWidth - truncatedRightWidth));
|
|
375
|
+
statsLine = leftStats + padding + truncatedRight;
|
|
376
|
+
} else {
|
|
377
|
+
statsLine = leftStats;
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
const lines = [
|
|
382
|
+
theme.fg("dim", statsLine),
|
|
383
|
+
truncateToWidth(theme.fg("dim", pwd), width, theme.fg("dim", "...")),
|
|
384
|
+
];
|
|
385
|
+
const extensionStatuses = footerData.getExtensionStatuses();
|
|
386
|
+
if (extensionStatuses.size > 0) {
|
|
387
|
+
const statusLine = Array.from(extensionStatuses.entries())
|
|
388
|
+
.sort(([a], [b]) => a.localeCompare(b))
|
|
389
|
+
.map(([, text]) => sanitizeStatusText(text))
|
|
390
|
+
.join(" ");
|
|
391
|
+
lines.push(truncateToWidth(statusLine, width, theme.fg("dim", "...")));
|
|
392
|
+
}
|
|
393
|
+
return lines;
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
function buildLimitsText(snapshot: LimitsSnapshot | undefined, width: number): string {
|
|
397
|
+
const compact = width < 110;
|
|
398
|
+
const barWidth = compact ? 8 : 10;
|
|
399
|
+
const separator = compact ? " | " : " ";
|
|
400
|
+
const primary = formatCompactWindow(snapshot?.primary?.label ?? "5h", snapshot?.primary?.remainingPercent ?? 0, snapshot?.primary?.resetsAtMs, barWidth);
|
|
401
|
+
const secondary = formatCompactWindow(compact ? "W" : snapshot?.secondary?.label ?? "Weekly", snapshot?.secondary?.remainingPercent ?? 0, snapshot?.secondary?.resetsAtMs, barWidth);
|
|
402
|
+
return `${primary}${separator}${secondary}`;
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
function sanitizeStatusText(text: string): string {
|
|
406
|
+
return text.replace(/[\r\n\t]/g, " ").replace(/ +/g, " ").trim();
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
function formatTokenCount(count: number): string {
|
|
410
|
+
if (count < 1000) return count.toString();
|
|
411
|
+
if (count < 10000) return `${(count / 1000).toFixed(1)}k`;
|
|
412
|
+
if (count < 1000000) return `${Math.round(count / 1000)}k`;
|
|
413
|
+
if (count < 10000000) return `${(count / 1000000).toFixed(1)}M`;
|
|
414
|
+
return `${Math.round(count / 1000000)}M`;
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
function formatCompactWindow(
|
|
418
|
+
label: string,
|
|
419
|
+
remainingPercent: number,
|
|
420
|
+
resetsAtMs: number | undefined,
|
|
421
|
+
barWidth: number,
|
|
422
|
+
): string {
|
|
423
|
+
const resetText = resetsAtMs ? formatResetTime(label, resetsAtMs) : "--:--";
|
|
424
|
+
return `${label} ${formatPercent(remainingPercent)} ${renderBar(remainingPercent, barWidth)} reset ${resetText}`;
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
function renderBar(remainingPercent: number, width: number): string {
|
|
428
|
+
const filled = Math.max(0, Math.min(width, Math.round((clamp(remainingPercent, 0, 100) / 100) * width)));
|
|
429
|
+
return `${"▰".repeat(filled)}${"▱".repeat(width - filled)}`;
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
function formatResetTime(label: string, timestampMs: number): string {
|
|
433
|
+
const date = new Date(timestampMs);
|
|
434
|
+
const now = new Date();
|
|
435
|
+
if (label === "Weekly" || label === "W") {
|
|
436
|
+
return `${formatMonth(date)} ${pad2(date.getDate())} ${formatTime(date)}`;
|
|
437
|
+
}
|
|
438
|
+
const dayDiff = differenceInCalendarDays(now, date);
|
|
439
|
+
if (dayDiff === 0) {
|
|
440
|
+
return formatTime(date);
|
|
441
|
+
}
|
|
442
|
+
if (dayDiff > 0 && dayDiff < 7) {
|
|
443
|
+
return `${formatWeekday(date)} ${formatTime(date)}`;
|
|
444
|
+
}
|
|
445
|
+
return `${formatMonth(date)} ${pad2(date.getDate())} ${formatTime(date)}`;
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
function differenceInCalendarDays(from: Date, to: Date): number {
|
|
449
|
+
const fromStart = new Date(from.getFullYear(), from.getMonth(), from.getDate()).getTime();
|
|
450
|
+
const toStart = new Date(to.getFullYear(), to.getMonth(), to.getDate()).getTime();
|
|
451
|
+
return Math.round((toStart - fromStart) / 86_400_000);
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
function formatWeekday(date: Date): string {
|
|
455
|
+
return ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"][date.getDay()] ?? "";
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
function formatMonth(date: Date): string {
|
|
459
|
+
return ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"][date.getMonth()] ?? "";
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
function formatTime(date: Date): string {
|
|
463
|
+
return `${pad2(date.getHours())}:${pad2(date.getMinutes())}`;
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
function pad2(value: number): string {
|
|
467
|
+
return value.toString().padStart(2, "0");
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
function formatPercent(value: number): string {
|
|
471
|
+
return `${Math.round(value)}%`;
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
function labelForWindow(windowMinutes: number | undefined, fallbackLabel: string): string {
|
|
475
|
+
if (windowMinutes === 300) {
|
|
476
|
+
return "5h";
|
|
477
|
+
}
|
|
478
|
+
if (windowMinutes === 10_080) {
|
|
479
|
+
return "Weekly";
|
|
480
|
+
}
|
|
481
|
+
if (windowMinutes === undefined) {
|
|
482
|
+
return fallbackLabel;
|
|
483
|
+
}
|
|
484
|
+
if (windowMinutes >= 60 && windowMinutes % 60 === 0) {
|
|
485
|
+
return `${windowMinutes / 60}h`;
|
|
486
|
+
}
|
|
487
|
+
return `${windowMinutes}m`;
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
function sanitizeNumber(value: number | undefined): number | undefined {
|
|
491
|
+
if (typeof value !== "number" || !Number.isFinite(value)) {
|
|
492
|
+
return undefined;
|
|
493
|
+
}
|
|
494
|
+
return value;
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
function secondsToMinutes(value: number | undefined): number | undefined {
|
|
498
|
+
const seconds = sanitizeNumber(value);
|
|
499
|
+
if (seconds === undefined || seconds <= 0) {
|
|
500
|
+
return undefined;
|
|
501
|
+
}
|
|
502
|
+
return Math.ceil(seconds / 60);
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
function secondsToMs(value: number | undefined): number | undefined {
|
|
506
|
+
const seconds = sanitizeNumber(value);
|
|
507
|
+
if (seconds === undefined || seconds <= 0) {
|
|
508
|
+
return undefined;
|
|
509
|
+
}
|
|
510
|
+
return seconds * 1000;
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
function clamp(value: number, min: number, max: number): number {
|
|
514
|
+
return Math.min(Math.max(value, min), max);
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
function normalizePlanType(value: string | undefined): string | undefined {
|
|
518
|
+
if (!value) {
|
|
519
|
+
return undefined;
|
|
520
|
+
}
|
|
521
|
+
return value.replace(/_/g, " ");
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
function ensureTrailingSlash(value: string): string {
|
|
525
|
+
return value.endsWith("/") ? value : `${value}/`;
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
function truncateInline(value: string, limit: number): string {
|
|
529
|
+
const normalized = value.replace(/\s+/g, " ").trim();
|
|
530
|
+
if (normalized.length <= limit) {
|
|
531
|
+
return normalized;
|
|
532
|
+
}
|
|
533
|
+
return `${normalized.slice(0, limit - 1)}…`;
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
async function safeReadText(response: Response): Promise<string> {
|
|
537
|
+
try {
|
|
538
|
+
return await response.text();
|
|
539
|
+
} catch {
|
|
540
|
+
return "";
|
|
541
|
+
}
|
|
542
|
+
}
|