pi-hud-plus 0.1.0 → 0.3.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 +22 -0
- package/README.md +78 -21
- package/package.json +1 -1
- package/src/clock.ts +4 -1
- package/src/commands.ts +215 -0
- package/src/config.ts +65 -17
- package/src/debug.ts +21 -0
- package/src/external-usage.ts +79 -0
- package/src/extra-cmd.ts +24 -5
- package/src/git.ts +38 -2
- package/src/i18n/en.ts +6 -0
- package/src/i18n/types.ts +6 -0
- package/src/i18n/zh-Hans.ts +6 -0
- package/src/index.ts +133 -16
- package/src/render/colors.ts +2 -3
- package/src/render/format-reset-time.ts +50 -0
- package/src/render/index.ts +6 -1
- package/src/render/lines/git.ts +53 -10
- package/src/render/lines/project.ts +1 -1
- package/src/render/lines/usage.ts +179 -0
- package/src/render/session-line.ts +113 -0
- package/src/sanitize.ts +1 -1
- package/src/speed-tracker.ts +2 -1
- package/src/types.ts +14 -0
- package/src/usage-vendors.ts +144 -0
|
@@ -1,4 +1,10 @@
|
|
|
1
|
+
import type { HudColorOverrides, TimeFormatMode, UsageValueMode } from "../config.ts";
|
|
2
|
+
import { t } from "../i18n/index.ts";
|
|
1
3
|
import type { RenderContext } from "../types.ts";
|
|
4
|
+
import { critical, label, quotaBar } from "./colors.ts";
|
|
5
|
+
import { formatResetTime } from "./format-reset-time.ts";
|
|
6
|
+
import { barWidth } from "./lines/context.ts";
|
|
7
|
+
import { formatUsagePercent, isLimitReached, limitResetAt, shownLongWindows } from "./lines/usage.ts";
|
|
2
8
|
import { renderEnvironmentLine } from "./lines/environment.ts";
|
|
3
9
|
import { renderContextParts } from "./lines/context.ts";
|
|
4
10
|
import { renderCompactGitPart, withGit } from "./lines/git.ts";
|
|
@@ -26,6 +32,7 @@ export function renderSessionLine(ctx: RenderContext): string | null {
|
|
|
26
32
|
renderSessionName(ctx),
|
|
27
33
|
renderVersion(ctx),
|
|
28
34
|
renderEnvironmentLine(ctx),
|
|
35
|
+
...renderUsageParts(ctx),
|
|
29
36
|
renderSessionTokensPart(ctx),
|
|
30
37
|
renderDuration(ctx),
|
|
31
38
|
renderSessionTimeLine(ctx),
|
|
@@ -40,3 +47,109 @@ export function renderSessionLine(ctx: RenderContext): string | null {
|
|
|
40
47
|
const withCustom = withCustomLine(parts, ctx);
|
|
41
48
|
return withCustom.length > 0 ? withCustom.join(" | ") : null;
|
|
42
49
|
}
|
|
50
|
+
|
|
51
|
+
type Colors = Partial<HudColorOverrides>;
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* claude-hud's session-line copy of the usage display, quirks kept: it passes timeFormat straight to formatResetTime
|
|
55
|
+
* (elapsed modes read as both), the weekly-only and limit-reached parts carry no Usage label, and bar mode shows
|
|
56
|
+
* `(2h / 5h)`. Monthly follows Weekly as in the usage Line.
|
|
57
|
+
*/
|
|
58
|
+
function renderUsageParts({ snapshot, config, width }: RenderContext): string[] {
|
|
59
|
+
const { display, colors } = config;
|
|
60
|
+
const usage = snapshot.usageLimit;
|
|
61
|
+
if (!display.showUsage || !usage) return [];
|
|
62
|
+
|
|
63
|
+
const now = snapshot.now ?? Date.now();
|
|
64
|
+
const { timeFormat, showResetLabel, usageCompact, usageValue: usageValueMode } = display;
|
|
65
|
+
const resetsKey = timeFormat === "absolute" ? "format.resets" : "format.resetsIn";
|
|
66
|
+
|
|
67
|
+
if (usage.balanceLabel) return [`${label(t("label.usage"), colors)} ${usage.balanceLabel}`];
|
|
68
|
+
|
|
69
|
+
if (isLimitReached(usage)) {
|
|
70
|
+
const resetTime = formatResetTime(limitResetAt(usage), timeFormat, now);
|
|
71
|
+
if (usageCompact) return [critical(`⚠ Limit${resetTime ? ` (${resetTime})` : ""}`, colors)];
|
|
72
|
+
const resetSuffix = resetTime ? (showResetLabel ? ` (${t(resetsKey)} ${resetTime})` : ` (${resetTime})`) : "";
|
|
73
|
+
return [critical(`⚠ ${t("status.limitReached")}${resetSuffix}`, colors)];
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const { fiveHour, sevenDay } = usage;
|
|
77
|
+
if (Math.max(fiveHour ?? 0, sevenDay ?? 0) < display.usageThreshold) return [];
|
|
78
|
+
|
|
79
|
+
const longParts = shownLongWindows(usage, display.sevenDayThreshold);
|
|
80
|
+
|
|
81
|
+
if (usageCompact) {
|
|
82
|
+
return [
|
|
83
|
+
fiveHour !== null ? formatCompactWindowPart("5h", fiveHour, usage.fiveHourResetAt, timeFormat, now, colors, usageValueMode) : null,
|
|
84
|
+
...longParts.map((w) => formatCompactWindowPart(w.short, w.percent, w.resetAt, timeFormat, now, colors, usageValueMode)),
|
|
85
|
+
].filter((part) => part !== null);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const common = { colors, usageBarEnabled: display.usageBarEnabled, barWidth: barWidth(width), timeFormat, now, showResetLabel, usageValueMode };
|
|
89
|
+
const longPart = (w: (typeof longParts)[number]) =>
|
|
90
|
+
formatUsageWindowPart({ ...common, label: t(w.key), percent: w.percent, resetAt: w.resetAt, forceLabel: true });
|
|
91
|
+
|
|
92
|
+
if (fiveHour === null && longParts.length > 0) return longParts.map(longPart);
|
|
93
|
+
|
|
94
|
+
const fiveHourPart = formatUsageWindowPart({ ...common, label: "5h", percent: fiveHour, resetAt: usage.fiveHourResetAt });
|
|
95
|
+
return [`${label(t("label.usage"), colors)} ${fiveHourPart}`, ...longParts.map(longPart)];
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function formatCompactWindowPart(
|
|
99
|
+
windowLabel: string,
|
|
100
|
+
percent: number | null,
|
|
101
|
+
resetAt: Date | null,
|
|
102
|
+
timeFormat: TimeFormatMode,
|
|
103
|
+
now: number,
|
|
104
|
+
colors?: Colors,
|
|
105
|
+
usageValueMode: UsageValueMode = "percent",
|
|
106
|
+
): string {
|
|
107
|
+
const usageDisplay = formatUsagePercent(percent, colors, usageValueMode);
|
|
108
|
+
const reset = formatResetTime(resetAt, timeFormat, now);
|
|
109
|
+
const styledLabel = label(`${windowLabel}:`, colors);
|
|
110
|
+
return reset ? `${styledLabel} ${usageDisplay} ${label(`(${reset})`, colors)}` : `${styledLabel} ${usageDisplay}`;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function formatUsageWindowPart({
|
|
114
|
+
label: windowLabel,
|
|
115
|
+
percent,
|
|
116
|
+
resetAt,
|
|
117
|
+
colors,
|
|
118
|
+
usageBarEnabled,
|
|
119
|
+
barWidth,
|
|
120
|
+
timeFormat,
|
|
121
|
+
now,
|
|
122
|
+
showResetLabel,
|
|
123
|
+
forceLabel = false,
|
|
124
|
+
usageValueMode,
|
|
125
|
+
}: {
|
|
126
|
+
label: string;
|
|
127
|
+
percent: number | null;
|
|
128
|
+
resetAt: Date | null;
|
|
129
|
+
colors?: Colors;
|
|
130
|
+
usageBarEnabled: boolean;
|
|
131
|
+
barWidth: number;
|
|
132
|
+
timeFormat: TimeFormatMode;
|
|
133
|
+
now: number;
|
|
134
|
+
showResetLabel: boolean;
|
|
135
|
+
forceLabel?: boolean;
|
|
136
|
+
usageValueMode: UsageValueMode;
|
|
137
|
+
}): string {
|
|
138
|
+
const usageDisplay = formatUsagePercent(percent, colors, usageValueMode);
|
|
139
|
+
const reset = formatResetTime(resetAt, timeFormat, now);
|
|
140
|
+
const styledLabel = label(windowLabel, colors);
|
|
141
|
+
// "resets in X" for relative/both; "resets X" for absolute (avoids "resets in at 14:30").
|
|
142
|
+
const resetsKey = timeFormat === "absolute" ? "format.resets" : "format.resetsIn";
|
|
143
|
+
|
|
144
|
+
if (usageBarEnabled) {
|
|
145
|
+
// Relative keeps claude-hud's "(duration / window)"; other modes use the preposition form.
|
|
146
|
+
const barReset =
|
|
147
|
+
timeFormat === "relative" ? (reset ? `${reset} / ${windowLabel}` : null) : reset ? (showResetLabel ? `${t(resetsKey)} ${reset}` : reset) : null;
|
|
148
|
+
const bar = quotaBar(percent ?? 0, barWidth, colors);
|
|
149
|
+
const body = barReset ? `${bar} ${usageDisplay} (${barReset})` : `${bar} ${usageDisplay}`;
|
|
150
|
+
return forceLabel ? `${styledLabel} ${body}` : body;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
const resetSuffix = reset ? (showResetLabel ? `(${t(resetsKey)} ${reset})` : `(${reset})`) : "";
|
|
154
|
+
return resetSuffix ? `${styledLabel} ${usageDisplay} ${resetSuffix}` : `${styledLabel} ${usageDisplay}`;
|
|
155
|
+
}
|
package/src/sanitize.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// eslint-disable-next-line no-control-regex
|
|
2
2
|
const CONTROL_AND_BIDI_PATTERN = /[\u0000-\u001F\u007F-\u009F\u061C\u200E\u200F\u202A-\u202E\u2066-\u2069\u206A-\u206F]/g;
|
|
3
3
|
|
|
4
|
-
/** Strips C0/C1 control and bidi characters so untrusted text (paths, names,
|
|
4
|
+
/** Strips C0/C1 control and bidi characters so untrusted text (paths, names, command output) can't inject escape codes. */
|
|
5
5
|
export function sanitize(value: string): string {
|
|
6
6
|
return value.replace(CONTROL_AND_BIDI_PATTERN, "");
|
|
7
7
|
}
|
package/src/speed-tracker.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// Ported from claude-hud's speed-tracker. pi streams to one process, so the previous sample lives in memory, not a cache file.
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
/** A reading older than this is stale. */
|
|
4
|
+
export const SPEED_WINDOW_MS = 2000;
|
|
4
5
|
// Updates can arrive many times per second while tokens stream. Computing a rate from
|
|
5
6
|
// sub-500ms windows amplifies noise and produces spurious multi-thousand tok/s readings,
|
|
6
7
|
// so require at least half a second of elapsed time before reporting a speed.
|
package/src/types.ts
CHANGED
|
@@ -50,6 +50,20 @@ export interface HudSnapshot {
|
|
|
50
50
|
memory?: MemoryInfo | null;
|
|
51
51
|
/** What shapes the agent's context. Absent: config counts off. */
|
|
52
52
|
environment?: HudEnvironment;
|
|
53
|
+
/** The current vendor's Usage limit or Balance. Absent or null: none, off, or not read yet. */
|
|
54
|
+
usageLimit?: UsageLimit | null;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** claude-hud's UsageData plus the monthly Limit window. Percents are 0-100; null = the vendor reports no such window. */
|
|
58
|
+
export interface UsageLimit {
|
|
59
|
+
fiveHour: number | null;
|
|
60
|
+
sevenDay: number | null;
|
|
61
|
+
monthly: number | null;
|
|
62
|
+
fiveHourResetAt: Date | null;
|
|
63
|
+
sevenDayResetAt: Date | null;
|
|
64
|
+
monthlyResetAt: Date | null;
|
|
65
|
+
/** A Balance (GLOSSARY.md, e.g. "¥4.12"), not a Limit window: carried here because claude-hud's UsageData shape holds it. Shown instead of the windows. */
|
|
66
|
+
balanceLabel?: string | null;
|
|
53
67
|
}
|
|
54
68
|
|
|
55
69
|
export interface HudEnvironment {
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
// Native Usage limits: one entry per vendor, detected from the current model. Adding a vendor = a detect plus a fetch.
|
|
2
|
+
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
import { createDebug } from "./debug.ts";
|
|
4
|
+
import { emptyUsageLimit, parseUsagePercent as percent, sanitizeBalanceLabel } from "./external-usage.ts";
|
|
5
|
+
import type { UsageLimit } from "./types.ts";
|
|
6
|
+
|
|
7
|
+
export type UsageModel = NonNullable<ExtensionContext["model"]>;
|
|
8
|
+
|
|
9
|
+
export interface UsageVendor {
|
|
10
|
+
/** From the model, not the provider id, so renamed and custom providers work. */
|
|
11
|
+
detect(model: UsageModel): boolean;
|
|
12
|
+
/** The vendor's Usage limit or Balance; null on any failure (logged, never thrown). */
|
|
13
|
+
fetch(model: UsageModel, apiKey: string): Promise<UsageLimit | null>;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const FETCH_TIMEOUT_MS = 10_000;
|
|
17
|
+
// Messages never include the key or response bodies.
|
|
18
|
+
const debug = createDebug("usage");
|
|
19
|
+
|
|
20
|
+
/** A guarded GET: the parsed JSON body, or null on timeout, network error, non-2xx or bad JSON. */
|
|
21
|
+
export async function fetchJson(url: string, headers: Record<string, string>, timeoutMs = FETCH_TIMEOUT_MS): Promise<unknown> {
|
|
22
|
+
try {
|
|
23
|
+
const response = await fetch(url, { headers, signal: AbortSignal.timeout(timeoutMs) });
|
|
24
|
+
if (!response.ok) {
|
|
25
|
+
debug(`GET ${url} failed with HTTP ${response.status}`);
|
|
26
|
+
return null;
|
|
27
|
+
}
|
|
28
|
+
return await response.json();
|
|
29
|
+
} catch (error) {
|
|
30
|
+
debug(`GET ${url} failed: ${(error as Error)?.name ?? "error"}`);
|
|
31
|
+
return null;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const isObject = (value: unknown): value is Record<string, unknown> => typeof value === "object" && value !== null;
|
|
36
|
+
|
|
37
|
+
/** Epoch seconds → Date; null when missing or ≤0. */
|
|
38
|
+
function resetDate(value: unknown): Date | null {
|
|
39
|
+
return typeof value === "number" && Number.isFinite(value) && value > 0 ? new Date(value * 1000) : null;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Codex windows mapped by length in minutes (300 → 5h, 10080 → weekly); any other length is dropped. */
|
|
43
|
+
function codexLimit(windows: unknown[], minutesOf: (window: Record<string, unknown>) => unknown): UsageLimit | null {
|
|
44
|
+
const usage = emptyUsageLimit();
|
|
45
|
+
for (const window of windows) {
|
|
46
|
+
if (!isObject(window)) continue;
|
|
47
|
+
const used = percent(window.used_percent);
|
|
48
|
+
if (used === null) continue;
|
|
49
|
+
const minutes = minutesOf(window);
|
|
50
|
+
if (minutes === 300) [usage.fiveHour, usage.fiveHourResetAt] = [used, resetDate(window.reset_at)];
|
|
51
|
+
else if (minutes === 10080) [usage.sevenDay, usage.sevenDayResetAt] = [used, resetDate(window.reset_at)];
|
|
52
|
+
}
|
|
53
|
+
return usage.fiveHour === null && usage.sevenDay === null ? null : usage;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** `GET wham/usage`'s body: `rate_limit.{primary_window, secondary_window}`, sized by limit_window_seconds. */
|
|
57
|
+
export function parseCodexUsage(body: unknown): UsageLimit | null {
|
|
58
|
+
if (!isObject(body) || !isObject(body.rate_limit)) return null;
|
|
59
|
+
const { primary_window, secondary_window } = body.rate_limit;
|
|
60
|
+
return codexLimit([primary_window, secondary_window], (w) => (typeof w.limit_window_seconds === "number" ? w.limit_window_seconds / 60 : null));
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** A `codex.rate_limits` stream frame: `rate_limits.{primary, secondary}`, sized by window_minutes. Null for any other frame. */
|
|
64
|
+
export function parseCodexRateLimits(data: unknown): UsageLimit | null {
|
|
65
|
+
if (!isObject(data) || data.type !== "codex.rate_limits" || !isObject(data.rate_limits)) return null;
|
|
66
|
+
const { primary, secondary } = data.rate_limits;
|
|
67
|
+
return codexLimit([primary, secondary], (w) => w.window_minutes);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export const codex: UsageVendor = {
|
|
71
|
+
detect: (model) => model.api === "openai-codex-responses",
|
|
72
|
+
async fetch(_model, apiKey) {
|
|
73
|
+
const usage = parseCodexUsage(await fetchJson("https://chatgpt.com/backend-api/wham/usage", { Authorization: `Bearer ${apiKey}` }));
|
|
74
|
+
if (!usage) debug("codex: no usable rate_limit in wham/usage");
|
|
75
|
+
return usage;
|
|
76
|
+
},
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
/** GLM `data.limits[]` pools, matched by type+unit+number (never index); any other pool is dropped. */
|
|
80
|
+
const GLM_WINDOWS: Record<string, "fiveHour" | "sevenDay" | "monthly"> = {
|
|
81
|
+
"TOKENS_LIMIT/3/5": "fiveHour",
|
|
82
|
+
"TOKENS_LIMIT/6/1": "sevenDay",
|
|
83
|
+
"TIME_LIMIT/5/1": "monthly",
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
/** `GET /api/monitor/usage/quota/limit`'s body: `data.limits[]` with `percentage` used and `nextResetTime` in epoch ms. */
|
|
87
|
+
export function parseGlmQuota(body: unknown): UsageLimit | null {
|
|
88
|
+
if (!isObject(body) || !isObject(body.data) || !Array.isArray(body.data.limits)) return null;
|
|
89
|
+
const usage = emptyUsageLimit();
|
|
90
|
+
for (const limit of body.data.limits) {
|
|
91
|
+
if (!isObject(limit)) continue;
|
|
92
|
+
const window = GLM_WINDOWS[`${limit.type}/${limit.unit}/${limit.number}`];
|
|
93
|
+
const used = percent(limit.percentage);
|
|
94
|
+
if (!window || used === null) continue;
|
|
95
|
+
usage[window] = used;
|
|
96
|
+
usage[`${window}ResetAt`] = typeof limit.nextResetTime === "number" ? resetDate(limit.nextResetTime / 1000) : null;
|
|
97
|
+
}
|
|
98
|
+
return usage.fiveHour === null && usage.sevenDay === null && usage.monthly === null ? null : usage;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** The quota host for a GLM model's baseUrl (CN or international), or undefined for any other model. */
|
|
102
|
+
function glmHost(model: UsageModel): string | undefined {
|
|
103
|
+
const host = URL.parse(model.baseUrl)?.hostname;
|
|
104
|
+
if (host === "open.bigmodel.cn" || host === "bigmodel.cn") return "https://open.bigmodel.cn";
|
|
105
|
+
if (host === "api.z.ai") return "https://api.z.ai"; // international host unverified live
|
|
106
|
+
return undefined;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export const glm: UsageVendor = {
|
|
110
|
+
detect: (model) => glmHost(model) !== undefined,
|
|
111
|
+
async fetch(model, apiKey) {
|
|
112
|
+
const url = `${glmHost(model)}/api/monitor/usage/quota/limit`;
|
|
113
|
+
// The raw key, no Bearer: the documented form.
|
|
114
|
+
const usage = parseGlmQuota(await fetchJson(url, { Authorization: apiKey, "Accept-Language": "en-US,en" }));
|
|
115
|
+
if (!usage) debug("glm: no usable limits in quota/limit");
|
|
116
|
+
return usage;
|
|
117
|
+
},
|
|
118
|
+
};
|
|
119
|
+
|
|
120
|
+
const CURRENCY_SYMBOLS: Record<string, string> = { CNY: "¥", USD: "$" };
|
|
121
|
+
|
|
122
|
+
/** `GET /user/balance`'s body: each `balance_infos` entry as `<symbol><total_balance>`, joined by a space. */
|
|
123
|
+
export function parseDeepSeekBalance(body: unknown): UsageLimit | null {
|
|
124
|
+
if (!isObject(body) || !Array.isArray(body.balance_infos)) return null;
|
|
125
|
+
const parts = body.balance_infos
|
|
126
|
+
.filter((info): info is Record<string, unknown> => isObject(info) && typeof info.currency === "string" && typeof info.total_balance === "string")
|
|
127
|
+
.map((info) => `${CURRENCY_SYMBOLS[info.currency as string] ?? `${info.currency} `}${info.total_balance}`);
|
|
128
|
+
const balanceLabel = sanitizeBalanceLabel(parts.join(" "));
|
|
129
|
+
if (!balanceLabel) return null;
|
|
130
|
+
return { ...emptyUsageLimit(), balanceLabel };
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export const deepseek: UsageVendor = {
|
|
134
|
+
detect: (model) => URL.parse(model.baseUrl)?.hostname === "api.deepseek.com",
|
|
135
|
+
async fetch(_model, apiKey) {
|
|
136
|
+
const usage = parseDeepSeekBalance(await fetchJson("https://api.deepseek.com/user/balance", { Authorization: `Bearer ${apiKey}` }));
|
|
137
|
+
if (!usage) debug("deepseek: no usable balance_infos in user/balance");
|
|
138
|
+
return usage;
|
|
139
|
+
},
|
|
140
|
+
};
|
|
141
|
+
|
|
142
|
+
const VENDORS: UsageVendor[] = [codex, glm, deepseek];
|
|
143
|
+
|
|
144
|
+
export const detectVendor = (model: UsageModel | undefined): UsageVendor | undefined => (model ? VENDORS.find((vendor) => vendor.detect(model)) : undefined);
|