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
package/src/index.ts
CHANGED
|
@@ -12,14 +12,17 @@ import {
|
|
|
12
12
|
type ToolExecutionStartEvent,
|
|
13
13
|
} from "@earendil-works/pi-coding-agent";
|
|
14
14
|
import { hasTickingElement, startClock } from "./clock.ts";
|
|
15
|
+
import { registerCommands } from "./commands.ts";
|
|
15
16
|
import { loadConfig, type HudConfig } from "./config.ts";
|
|
17
|
+
import { getUsageFromExternalSnapshot } from "./external-usage.ts";
|
|
16
18
|
import { runExtraCmd } from "./extra-cmd.ts";
|
|
17
|
-
import { getGitStatus } from "./git.ts";
|
|
19
|
+
import { getGitStatus, type GitStatusOptions } from "./git.ts";
|
|
18
20
|
import { getMemoryUsage } from "./memory.ts";
|
|
19
21
|
import { renderHud } from "./render/index.ts";
|
|
20
22
|
import { createSessionReader } from "./session.ts";
|
|
21
|
-
import { createSpeedTracker } from "./speed-tracker.ts";
|
|
22
|
-
import type { HudContext, HudEnvironment, HudSnapshot, HudTool } from "./types.ts";
|
|
23
|
+
import { createSpeedTracker, SPEED_WINDOW_MS } from "./speed-tracker.ts";
|
|
24
|
+
import type { HudContext, HudEnvironment, HudSnapshot, HudTool, UsageLimit } from "./types.ts";
|
|
25
|
+
import { codex, detectVendor, parseCodexRateLimits, type UsageModel } from "./usage-vendors.ts";
|
|
23
26
|
|
|
24
27
|
interface Session {
|
|
25
28
|
generation: number;
|
|
@@ -30,8 +33,12 @@ interface Session {
|
|
|
30
33
|
displacedNotice?: ReturnType<typeof setTimeout>;
|
|
31
34
|
stopClock?: () => void;
|
|
32
35
|
trackSpeed: ReturnType<typeof createSpeedTracker>;
|
|
36
|
+
/** Hides the speed once its reading is stale. */
|
|
37
|
+
speedExpiry?: ReturnType<typeof setTimeout>;
|
|
33
38
|
git?: BackgroundJob;
|
|
34
39
|
extra?: BackgroundJob;
|
|
40
|
+
/** Absent when showUsage is off. */
|
|
41
|
+
usage?: UsageJob;
|
|
35
42
|
footerData?: ReadonlyFooterDataProvider;
|
|
36
43
|
/** Context from the streaming reply's usage; wins over getContextUsage() until a clearing event. */
|
|
37
44
|
liveContext?: HudContext;
|
|
@@ -96,6 +103,19 @@ interface BackgroundJob {
|
|
|
96
103
|
const GIT_THROTTLE_MS = 2000;
|
|
97
104
|
const GIT_BACKSTOP_MS = 30_000;
|
|
98
105
|
const EXTRA_BACKSTOP_MS = 30_000;
|
|
106
|
+
/** A fetch is skipped while the current vendor's data is younger than this. */
|
|
107
|
+
const USAGE_SKIP_MS = 60_000;
|
|
108
|
+
const USAGE_BACKSTOP_MS = 5 * 60_000;
|
|
109
|
+
|
|
110
|
+
/** The usage job: the current vendor's Usage limit, else the External usage snapshot. */
|
|
111
|
+
interface UsageJob extends BackgroundJob {
|
|
112
|
+
/** The model changed; another vendor clears the shown data until its own arrives. */
|
|
113
|
+
selectModel(model: UsageModel): void;
|
|
114
|
+
/** A provider stream frame; Codex's codex.rate_limits carries its Usage limit. */
|
|
115
|
+
frame(data: unknown): void;
|
|
116
|
+
/** Re-shows the data, re-reading the External usage snapshot (for freshness) while there's no native data. */
|
|
117
|
+
show(): void;
|
|
118
|
+
}
|
|
99
119
|
|
|
100
120
|
// On globalThis, not module scope: /reload re-imports this module, and the notice must fire once per pi process.
|
|
101
121
|
const NOTICE_SHOWN = Symbol.for("pi-hud-plus.displacedNoticeShown");
|
|
@@ -107,6 +127,7 @@ const DISPLACED_NOTICE =
|
|
|
107
127
|
|
|
108
128
|
/** Pi adapter: owns the footer and keeps the cached HUD snapshot up to date. */
|
|
109
129
|
export default function piHud(pi: ExtensionAPI): void {
|
|
130
|
+
registerCommands(pi);
|
|
110
131
|
// Bumped on every session start/shutdown. Async work captures it and checks isLive(gen) before touching anything.
|
|
111
132
|
let generation = 0;
|
|
112
133
|
let session: Session | undefined;
|
|
@@ -143,7 +164,7 @@ export default function piHud(pi: ExtensionAPI): void {
|
|
|
143
164
|
const readSession = createSessionReader();
|
|
144
165
|
|
|
145
166
|
/** Async git refresh: at most one run in flight, triggers coalesced, runs spaced by the throttle, plus a backstop. */
|
|
146
|
-
const startGitJob = (gen: number, cwd: string, footerData: ReadonlyFooterDataProvider, options:
|
|
167
|
+
const startGitJob = (gen: number, cwd: string, footerData: ReadonlyFooterDataProvider, options: GitStatusOptions): BackgroundJob => {
|
|
147
168
|
let inFlight = false;
|
|
148
169
|
let pending = false;
|
|
149
170
|
let lastRun = -Infinity;
|
|
@@ -213,9 +234,80 @@ export default function piHud(pi: ExtensionAPI): void {
|
|
|
213
234
|
return { trigger: () => void run(), stop: () => clearInterval(backstop) };
|
|
214
235
|
};
|
|
215
236
|
|
|
237
|
+
/** Usage refresh: on trigger and a backstop, at most one fetch in flight, skipped while the data is fresh. Never from render. */
|
|
238
|
+
const startUsageJob = (
|
|
239
|
+
gen: number,
|
|
240
|
+
config: HudConfig,
|
|
241
|
+
model: UsageModel | undefined,
|
|
242
|
+
registry: ExtensionContext["modelRegistry"],
|
|
243
|
+
onShown: () => void,
|
|
244
|
+
): UsageJob => {
|
|
245
|
+
let vendor = detectVendor(model);
|
|
246
|
+
let native: UsageLimit | null = null;
|
|
247
|
+
// The last fetch attempt (success or failure) or frame: a vendor that's down gets at most one request per USAGE_SKIP_MS.
|
|
248
|
+
let freshAt = -Infinity;
|
|
249
|
+
// Bumped on a vendor switch or a frame: an in-flight fetch is then ignored (it predates the data) and doesn't block a new one.
|
|
250
|
+
let epoch = 0;
|
|
251
|
+
let inFlight: number | undefined;
|
|
252
|
+
|
|
253
|
+
const show = () => {
|
|
254
|
+
if (!isLive(gen)) return;
|
|
255
|
+
const usageLimit = native ?? getUsageFromExternalSnapshot(config);
|
|
256
|
+
if (JSON.stringify(usageLimit) !== JSON.stringify(session!.snapshot.usageLimit ?? null)) update(gen, { usageLimit });
|
|
257
|
+
onShown();
|
|
258
|
+
};
|
|
259
|
+
const setNative = (usage: UsageLimit | null) => {
|
|
260
|
+
native = usage;
|
|
261
|
+
show();
|
|
262
|
+
};
|
|
263
|
+
|
|
264
|
+
const run = async () => {
|
|
265
|
+
show();
|
|
266
|
+
if (!isLive(gen) || !vendor || !model || inFlight === epoch || Date.now() - freshAt < USAGE_SKIP_MS) return;
|
|
267
|
+
const mine = (inFlight = epoch);
|
|
268
|
+
freshAt = Date.now();
|
|
269
|
+
const [current, forModel] = [vendor, model];
|
|
270
|
+
const usage = await registry
|
|
271
|
+
.getApiKeyAndHeaders(forModel)
|
|
272
|
+
.then((auth) => (auth.ok && auth.apiKey ? current.fetch(forModel, auth.apiKey) : null))
|
|
273
|
+
.catch(() => null);
|
|
274
|
+
if (inFlight === mine) inFlight = undefined;
|
|
275
|
+
if (mine === epoch && isLive(gen)) setNative(usage);
|
|
276
|
+
};
|
|
277
|
+
|
|
278
|
+
const backstop = setInterval(() => void run(), USAGE_BACKSTOP_MS);
|
|
279
|
+
backstop.unref?.();
|
|
280
|
+
void run();
|
|
281
|
+
return {
|
|
282
|
+
trigger: () => void run(),
|
|
283
|
+
stop: () => clearInterval(backstop),
|
|
284
|
+
show,
|
|
285
|
+
selectModel(next) {
|
|
286
|
+
const nextVendor = detectVendor(next);
|
|
287
|
+
// Another baseUrl host is another account (GLM's open.bigmodel.cn vs api.z.ai), so its data is another's too.
|
|
288
|
+
const switched = nextVendor !== vendor || URL.parse(next.baseUrl)?.hostname !== URL.parse(model?.baseUrl ?? "")?.hostname;
|
|
289
|
+
model = next;
|
|
290
|
+
if (switched) {
|
|
291
|
+
vendor = nextVendor;
|
|
292
|
+
epoch++;
|
|
293
|
+
native = null;
|
|
294
|
+
freshAt = -Infinity;
|
|
295
|
+
}
|
|
296
|
+
void run();
|
|
297
|
+
},
|
|
298
|
+
frame(data) {
|
|
299
|
+
const usage = vendor === codex ? parseCodexRateLimits(data) : null;
|
|
300
|
+
if (!usage || !isLive(gen)) return;
|
|
301
|
+
epoch++;
|
|
302
|
+
freshAt = Date.now();
|
|
303
|
+
setNative(usage);
|
|
304
|
+
},
|
|
305
|
+
};
|
|
306
|
+
};
|
|
307
|
+
|
|
216
308
|
pi.on("session_start", (_event, ctx: ExtensionContext) => {
|
|
217
309
|
if (!ctx.hasUI || ctx.mode !== "tui") return;
|
|
218
|
-
const config = loadConfig(
|
|
310
|
+
const config = loadConfig(getAgentDir());
|
|
219
311
|
const breakdown = lastBreakdown(ctx.sessionManager.getEntries());
|
|
220
312
|
const current: Session = (session = {
|
|
221
313
|
generation: ++generation,
|
|
@@ -238,18 +330,31 @@ export default function piHud(pi: ExtensionAPI): void {
|
|
|
238
330
|
tools: new Map(),
|
|
239
331
|
breakdown,
|
|
240
332
|
});
|
|
241
|
-
|
|
242
|
-
current.
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
333
|
+
const tick = (now: number) => {
|
|
334
|
+
update(current.generation, { now });
|
|
335
|
+
current.usage?.show();
|
|
336
|
+
// Memory is sampled here, never in render; the first reading lands on the first tick.
|
|
337
|
+
if (config.display.showMemoryUsage) void getMemoryUsage().then((memory) => update(current.generation, { memory }));
|
|
338
|
+
};
|
|
339
|
+
// A shown Limit window's reset countdown ticks too; a Balance hides the windows, so it doesn't.
|
|
340
|
+
const syncClock = () => {
|
|
341
|
+
const u = current.snapshot.usageLimit;
|
|
342
|
+
const counting = !!u && !u.balanceLabel && !!(u.fiveHourResetAt || u.sevenDayResetAt || u.monthlyResetAt);
|
|
343
|
+
const wanted = hasTickingElement(config) || counting;
|
|
344
|
+
if (!isLive(current.generation) || wanted === !!current.stopClock) return;
|
|
345
|
+
if (wanted) current.stopClock = startClock(tick);
|
|
346
|
+
else {
|
|
347
|
+
current.stopClock!();
|
|
348
|
+
current.stopClock = undefined;
|
|
349
|
+
}
|
|
350
|
+
};
|
|
351
|
+
if (config.display.showUsage) current.usage = startUsageJob(current.generation, config, ctx.model, ctx.modelRegistry, syncClock);
|
|
352
|
+
syncClock();
|
|
248
353
|
setFooter(ctx.ui, (tui, _theme, footerData) => {
|
|
249
354
|
current.requestRender = () => tui.requestRender();
|
|
250
355
|
current.footerData = footerData;
|
|
251
356
|
current.snapshot = { ...current.snapshot, model: modelInfo(ctx.model, footerData) };
|
|
252
|
-
if (config.gitStatus.enabled) current.git = startGitJob(current.generation, ctx.cwd, footerData, config.gitStatus);
|
|
357
|
+
if (config.gitStatus.enabled) current.git = startGitJob(current.generation, ctx.cwd, footerData, { ...config.gitStatus, linkBranch: config.lineLayout === "expanded" });
|
|
253
358
|
return {
|
|
254
359
|
// Statuses are read live: pi requests a render whenever an extension sets one.
|
|
255
360
|
render: (width) => renderHud({ ...current.snapshot, extensionStatuses: footerData.getExtensionStatuses() }, config, width),
|
|
@@ -260,6 +365,7 @@ export default function piHud(pi: ExtensionAPI): void {
|
|
|
260
365
|
current.stopClock?.();
|
|
261
366
|
current.git?.stop();
|
|
262
367
|
current.extra?.stop();
|
|
368
|
+
current.usage?.stop();
|
|
263
369
|
current.displacedNotice = setTimeout(() => {
|
|
264
370
|
if (globals[NOTICE_SHOWN]) return;
|
|
265
371
|
globals[NOTICE_SHOWN] = true;
|
|
@@ -276,13 +382,19 @@ export default function piHud(pi: ExtensionAPI): void {
|
|
|
276
382
|
// Session data: after these events the session's entries or name may have changed.
|
|
277
383
|
const refreshSession = (ctx: ExtensionContext) => update(generation, { session: readSession(pi, ctx), now: Date.now() });
|
|
278
384
|
|
|
279
|
-
// Speed: sampled from the streaming reply. Most updates come too close together for a reading; keep showing the last one
|
|
385
|
+
// Speed: sampled from the streaming reply. Most updates come too close together for a reading; keep showing the last one
|
|
386
|
+
// until it's stale, as claude-hud hides the speed once a reply stalls past the window.
|
|
280
387
|
const sampleSpeed = (s: Session, usage: Usage) => {
|
|
281
388
|
const speed = s.trackSpeed(usage.output, Date.now());
|
|
282
|
-
if (speed
|
|
389
|
+
if (speed === null) return;
|
|
390
|
+
update(generation, { speed });
|
|
391
|
+
clearTimeout(s.speedExpiry);
|
|
392
|
+
s.speedExpiry = setTimeout(() => live() === s && clearSpeed(s), SPEED_WINDOW_MS);
|
|
393
|
+
s.speedExpiry.unref?.();
|
|
283
394
|
};
|
|
284
395
|
// The reply stopped streaming: no fresh reading, so claude-hud would hide the speed.
|
|
285
396
|
const clearSpeed = (s: Session) => {
|
|
397
|
+
clearTimeout(s.speedExpiry);
|
|
286
398
|
if (s.snapshot.speed !== undefined) update(generation, { speed: undefined });
|
|
287
399
|
};
|
|
288
400
|
|
|
@@ -339,7 +451,9 @@ export default function piHud(pi: ExtensionAPI): void {
|
|
|
339
451
|
session: readSession(pi, ctx, event.model),
|
|
340
452
|
});
|
|
341
453
|
clearLiveContext(s, ctx);
|
|
454
|
+
s.usage?.selectModel(event.model);
|
|
342
455
|
});
|
|
456
|
+
pi.on("provider_stream_event", (event) => live()?.usage?.frame(event.data));
|
|
343
457
|
// The run's system prompt options are what the agent actually loaded.
|
|
344
458
|
pi.on("before_agent_start", (event) => {
|
|
345
459
|
if (!live()?.snapshot.environment) return;
|
|
@@ -388,6 +502,7 @@ export default function piHud(pi: ExtensionAPI): void {
|
|
|
388
502
|
clearSpeed(s);
|
|
389
503
|
s.git?.trigger();
|
|
390
504
|
s.extra?.trigger();
|
|
505
|
+
s.usage?.trigger();
|
|
391
506
|
clearLiveContext(s, ctx);
|
|
392
507
|
});
|
|
393
508
|
pi.on("session_info_changed", (_event, ctx) => {
|
|
@@ -405,11 +520,13 @@ export default function piHud(pi: ExtensionAPI): void {
|
|
|
405
520
|
|
|
406
521
|
pi.on("session_shutdown", (_event, ctx) => {
|
|
407
522
|
if (!session) return;
|
|
408
|
-
const { displaced, displacedNotice, stopClock } = session;
|
|
523
|
+
const { displaced, displacedNotice, speedExpiry, stopClock } = session;
|
|
409
524
|
clearTimeout(displacedNotice);
|
|
525
|
+
clearTimeout(speedExpiry);
|
|
410
526
|
stopClock?.();
|
|
411
527
|
session.git?.stop();
|
|
412
528
|
session.extra?.stop();
|
|
529
|
+
session.usage?.stop();
|
|
413
530
|
session = undefined;
|
|
414
531
|
generation++;
|
|
415
532
|
// Only while we still own the footer: otherwise this would wipe the other extension's footer.
|
package/src/render/colors.ts
CHANGED
|
@@ -133,11 +133,10 @@ export function getContextColor(
|
|
|
133
133
|
return resolveAnsi(colors?.context, GREEN);
|
|
134
134
|
}
|
|
135
135
|
|
|
136
|
-
/** claude-hud's quota colours; the usage overrides are gone, so only critical is configurable. */
|
|
137
136
|
export function getQuotaColor(percent: number, colors?: Partial<HudColorOverrides>): string {
|
|
138
137
|
if (percent >= 90) return resolveAnsi(colors?.critical, RED);
|
|
139
|
-
if (percent >= 75) return BRIGHT_MAGENTA;
|
|
140
|
-
return BRIGHT_BLUE;
|
|
138
|
+
if (percent >= 75) return resolveAnsi(colors?.usageWarning, BRIGHT_MAGENTA);
|
|
139
|
+
return resolveAnsi(colors?.usage, BRIGHT_BLUE);
|
|
141
140
|
}
|
|
142
141
|
|
|
143
142
|
export function quotaBar(percent: number, width: number = 10, colors?: Partial<HudColorOverrides>): string {
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import type { TimeFormatMode } from "../config.ts";
|
|
2
|
+
import { t } from "../i18n/index.ts";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* claude-hud's reset time for a Limit window, against `now` (the snapshot's clock) instead of `new Date()`.
|
|
6
|
+
* relative `2h 30m`, absolute `at 14:30` (date added on another day), anything else both: `2h 30m, at 14:30`.
|
|
7
|
+
* Empty when the reset is unknown or past.
|
|
8
|
+
*/
|
|
9
|
+
export function formatResetTime(resetAt: Date | null, mode: TimeFormatMode = "relative", now: number = Date.now()): string {
|
|
10
|
+
if (!resetAt) return "";
|
|
11
|
+
|
|
12
|
+
const diffMs = resetAt.getTime() - now;
|
|
13
|
+
if (diffMs <= 0) return "";
|
|
14
|
+
|
|
15
|
+
if (mode === "relative") return formatRelative(diffMs);
|
|
16
|
+
|
|
17
|
+
const absolute = formatAbsolute(resetAt, new Date(now));
|
|
18
|
+
if (mode === "absolute") return absolute;
|
|
19
|
+
|
|
20
|
+
// A comma, not parentheses: callers wrap the result in their own (...).
|
|
21
|
+
return `${formatRelative(diffMs)}, ${absolute}`;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function formatRelative(diffMs: number): string {
|
|
25
|
+
const diffMins = Math.ceil(diffMs / 60000);
|
|
26
|
+
if (diffMins < 60) return `${diffMins}m`;
|
|
27
|
+
|
|
28
|
+
const hours = Math.floor(diffMins / 60);
|
|
29
|
+
const mins = diffMins % 60;
|
|
30
|
+
|
|
31
|
+
if (hours >= 24) {
|
|
32
|
+
const days = Math.floor(hours / 24);
|
|
33
|
+
const remHours = hours % 24;
|
|
34
|
+
return remHours > 0 ? `${days}d ${remHours}h` : `${days}d`;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
return mins > 0 ? `${hours}h ${mins}m` : `${hours}h`;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function formatAbsolute(resetAt: Date, now: Date): string {
|
|
41
|
+
// Locales that bake the preposition into format.resets (zh: 重置于) set format.at to "".
|
|
42
|
+
const at = t("format.at");
|
|
43
|
+
const prefix = at ? `${at} ` : "";
|
|
44
|
+
const timeStr = resetAt.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
|
|
45
|
+
|
|
46
|
+
if (resetAt.toDateString() === now.toDateString()) return `${prefix}${timeStr}`;
|
|
47
|
+
|
|
48
|
+
const dateStr = resetAt.toLocaleDateString([], { month: "short", day: "numeric" });
|
|
49
|
+
return `${prefix}${dateStr} ${timeStr}`;
|
|
50
|
+
}
|
package/src/render/index.ts
CHANGED
|
@@ -5,6 +5,7 @@ import type { HudSnapshot, RenderContext } from "../types.ts";
|
|
|
5
5
|
import { dim } from "./colors.ts";
|
|
6
6
|
import { renderEnvironmentLine } from "./lines/environment.ts";
|
|
7
7
|
import { renderContextLine } from "./lines/context.ts";
|
|
8
|
+
import { renderGitFilesLine } from "./lines/git.ts";
|
|
8
9
|
import { renderMemoryLine } from "./lines/memory.ts";
|
|
9
10
|
import { renderPromptCacheLine } from "./lines/prompt-cache.ts";
|
|
10
11
|
import { renderProjectLine } from "./lines/project.ts";
|
|
@@ -12,12 +13,14 @@ import { renderSessionTimeLine } from "./lines/session-time.ts";
|
|
|
12
13
|
import { renderSessionTokensLine } from "./lines/session-stats.ts";
|
|
13
14
|
import { renderSessionLine } from "./session-line.ts";
|
|
14
15
|
import { renderToolsLine } from "./tools-line.ts";
|
|
16
|
+
import { renderUsageLine } from "./lines/usage.ts";
|
|
15
17
|
|
|
16
18
|
|
|
17
19
|
/** One Line module per Element. */
|
|
18
20
|
const ELEMENT_RENDERERS: Record<HudElement, (ctx: RenderContext) => string | null> = {
|
|
19
21
|
project: renderProjectLine,
|
|
20
22
|
context: renderContextLine,
|
|
23
|
+
usage: renderUsageLine,
|
|
21
24
|
promptCache: renderPromptCacheLine,
|
|
22
25
|
memory: renderMemoryLine,
|
|
23
26
|
environment: renderEnvironmentLine,
|
|
@@ -112,7 +115,9 @@ function renderExpanded(ctx: RenderContext): Array<{ line: string; isActivity: b
|
|
|
112
115
|
lines.push({ line, isActivity: ACTIVITY_ELEMENTS.has(element) });
|
|
113
116
|
}
|
|
114
117
|
|
|
115
|
-
// claude-hud
|
|
118
|
+
// Last of the Element Lines, as in claude-hud; the token and extension status Lines still follow.
|
|
119
|
+
const gitFilesLine = renderGitFilesLine(ctx);
|
|
120
|
+
if (gitFilesLine) lines.push({ line: gitFilesLine, isActivity: false });
|
|
116
121
|
return lines;
|
|
117
122
|
}
|
|
118
123
|
|
package/src/render/lines/git.ts
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
1
1
|
// Ported from claude-hud: the gitPart of render/lines/project.ts (expanded) and render/session-line.ts (compact).
|
|
2
|
-
//
|
|
2
|
+
// renderGitFilesLine and the branch link are ported from project.ts.
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { pathToFileURL } from "node:url";
|
|
3
5
|
import type { HudConfig } from "../../config.ts";
|
|
6
|
+
import type { LineDiff } from "../../git.ts";
|
|
4
7
|
import type { RenderContext } from "../../types.ts";
|
|
5
|
-
import { git as gitColor, gitBranch as gitBranchColor, warning as warningColor, critical as criticalColor, red, green } from "../colors.ts";
|
|
8
|
+
import { git as gitColor, gitBranch as gitBranchColor, warning as warningColor, critical as criticalColor, red, green, yellow, dim } from "../colors.ts";
|
|
6
9
|
import { sanitize } from "../../sanitize.ts";
|
|
7
10
|
|
|
8
11
|
/** The project Line's `git:(branch* ↑1 ↓2 [+3 -4])` segment, or null when git is off or there is no status. */
|
|
@@ -13,20 +16,16 @@ export function renderGitPart({ snapshot, config }: RenderContext): string | nul
|
|
|
13
16
|
if (!gitConfig.enabled || !status) return null;
|
|
14
17
|
|
|
15
18
|
const branchText = sanitize(status.branch + (gitConfig.showDirty && status.isDirty ? "*" : ""));
|
|
16
|
-
const
|
|
19
|
+
const branchUrl = status.githubUrl && `${status.githubUrl}/tree/${encodeURIComponent(status.branch)}`;
|
|
20
|
+
const gitInner: string[] = [safeHyperlink(branchUrl, gitBranchColor(branchText, colors))];
|
|
17
21
|
|
|
18
22
|
if (gitConfig.showAheadBehind) {
|
|
19
23
|
if (status.ahead > 0) gitInner.push(formatAheadCount(status.ahead, gitConfig, colors));
|
|
20
24
|
if (status.behind > 0) gitInner.push(gitBranchColor(`↓${status.behind}`, colors));
|
|
21
25
|
}
|
|
22
26
|
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
const diffParts: string[] = [];
|
|
26
|
-
if (added > 0) diffParts.push(green(`+${added}`));
|
|
27
|
-
if (deleted > 0) diffParts.push(red(`-${deleted}`));
|
|
28
|
-
if (diffParts.length > 0) gitInner.push(`[${diffParts.join(" ")}]`);
|
|
29
|
-
}
|
|
27
|
+
const diffParts = gitConfig.showFileStats ? lineDiffParts(status.lineDiff) : "";
|
|
28
|
+
if (diffParts) gitInner.push(`[${diffParts}]`);
|
|
30
29
|
|
|
31
30
|
return `${gitColor("git:(", colors)}${gitInner.join(" ")}${gitColor(")", colors)}`;
|
|
32
31
|
}
|
|
@@ -56,12 +55,56 @@ export function renderCompactGitPart({ snapshot, config }: RenderContext): strin
|
|
|
56
55
|
return `${gitColor("git:(", config.colors)}${gitBranchColor(sanitize(gitParts.join("")), config.colors)}${gitColor(")", config.colors)}`;
|
|
57
56
|
}
|
|
58
57
|
|
|
58
|
+
/** The git files Line: up to 6 changed files, newest first, each linked (OSC 8) when inside cwd. Expanded layout only. */
|
|
59
|
+
export function renderGitFilesLine({ snapshot, config, width }: RenderContext): string | null {
|
|
60
|
+
const fileStats = snapshot.git?.fileStats;
|
|
61
|
+
if (!config.gitStatus.enabled || !config.gitStatus.showFileStats || !fileStats || width < 60) return null;
|
|
62
|
+
const { trackedFiles, untracked } = fileStats;
|
|
63
|
+
if (trackedFiles.length === 0 && untracked === 0) return null;
|
|
64
|
+
|
|
65
|
+
const parts = trackedFiles.slice(0, 6).map((file) => {
|
|
66
|
+
const color = file.type === "added" ? green : file.type === "deleted" ? red : yellow;
|
|
67
|
+
const prefix = file.type === "added" ? "+" : file.type === "deleted" ? "-" : "~";
|
|
68
|
+
const name = color(sanitize(file.basename));
|
|
69
|
+
const resolved = path.resolve(fileStats.root ?? snapshot.cwd, file.fullPath);
|
|
70
|
+
const relative = path.relative(snapshot.cwd, resolved);
|
|
71
|
+
const inCwd = relative !== "" && relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
|
|
72
|
+
const diffParts = lineDiffParts(file.lineDiff);
|
|
73
|
+
return color(prefix) + (inCwd ? safeHyperlink(pathToFileURL(resolved).href, name) : name) + (diffParts ? dim(`(${diffParts})`) : "");
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
if (trackedFiles.length > 6) parts.push(dim(`+${trackedFiles.length - 6} more`));
|
|
77
|
+
if (untracked > 0) parts.push(dim(`?${untracked}`));
|
|
78
|
+
return parts.join(" ");
|
|
79
|
+
}
|
|
80
|
+
|
|
59
81
|
/** Project and git as Line parts: one part (`project git:(…)`), or two when `branchOverflow` is "wrap". */
|
|
60
82
|
export function withGit(project: string | null, git: string | null, config: HudConfig): string[] {
|
|
61
83
|
if (project && git && config.gitStatus.branchOverflow === "truncate") return [`${project} ${git}`];
|
|
62
84
|
return [project, git].filter((part) => part !== null);
|
|
63
85
|
}
|
|
64
86
|
|
|
87
|
+
/** `+3 -4` in green and red, skipping zeros; "" when there's nothing to show. */
|
|
88
|
+
function lineDiffParts(diff: LineDiff | undefined): string {
|
|
89
|
+
if (!diff) return "";
|
|
90
|
+
const parts: string[] = [];
|
|
91
|
+
if (diff.added > 0) parts.push(green(`+${diff.added}`));
|
|
92
|
+
if (diff.deleted > 0) parts.push(red(`-${diff.deleted}`));
|
|
93
|
+
return parts.join(" ");
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** OSC 8 link, or the plain text when the URI isn't a valid https/file URL. URL parsing percent-encodes control characters. */
|
|
97
|
+
function safeHyperlink(uri: string | undefined, text: string): string {
|
|
98
|
+
if (!uri) return text;
|
|
99
|
+
try {
|
|
100
|
+
const parsed = new URL(sanitize(uri));
|
|
101
|
+
if (parsed.protocol !== "https:" && parsed.protocol !== "file:") return text;
|
|
102
|
+
return `\x1b]8;;${parsed}\x1b\\${text}\x1b]8;;\x1b\\`;
|
|
103
|
+
} catch {
|
|
104
|
+
return text;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
65
108
|
function formatAheadCount(ahead: number, gitConfig: HudConfig["gitStatus"], colors: HudConfig["colors"]): string {
|
|
66
109
|
const value = `↑${ahead}`;
|
|
67
110
|
if (gitConfig.pushCriticalThreshold > 0 && ahead >= gitConfig.pushCriticalThreshold) return criticalColor(value, colors);
|
|
@@ -23,7 +23,7 @@ export function renderModelBadge({ snapshot, config }: RenderContext): string |
|
|
|
23
23
|
const level = snapshot.thinkingLevel;
|
|
24
24
|
const symbol = level && THINKING_SYMBOLS[level];
|
|
25
25
|
if (config.display.showThinkingLevel && symbol) badge += ` ${symbol} ${level}`;
|
|
26
|
-
//
|
|
26
|
+
// The model name comes from pi's model registry, which may hold user-defined models.
|
|
27
27
|
return modelColor(`[${sanitize(badge)}]`, config.colors);
|
|
28
28
|
}
|
|
29
29
|
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
import type { HudColorOverrides, TimeFormatMode, UsageValueMode } from "../../config.ts";
|
|
2
|
+
import { t } from "../../i18n/index.ts";
|
|
3
|
+
import type { RenderContext, UsageLimit } from "../../types.ts";
|
|
4
|
+
import { critical, getQuotaColor, label, quotaBar, RESET } from "../colors.ts";
|
|
5
|
+
import { formatResetTime } from "../format-reset-time.ts";
|
|
6
|
+
import { barWidth } from "./context.ts";
|
|
7
|
+
|
|
8
|
+
const FIVE_HOUR_WINDOW_MS = 5 * 60 * 60 * 1000;
|
|
9
|
+
const SEVEN_DAY_WINDOW_MS = 7 * 24 * 60 * 60 * 1000;
|
|
10
|
+
// GLM's monthly pool is a calendar month; 30 days is close enough for the elapsed share.
|
|
11
|
+
const MONTHLY_WINDOW_MS = 30 * 24 * 60 * 60 * 1000;
|
|
12
|
+
|
|
13
|
+
type Colors = Partial<HudColorOverrides>;
|
|
14
|
+
|
|
15
|
+
/** claude-hud's isLimitReached, with the monthly window. */
|
|
16
|
+
export function isLimitReached(usage: UsageLimit): boolean {
|
|
17
|
+
return usage.fiveHour === 100 || usage.sevenDay === 100 || usage.monthly === 100;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** The full window's reset, 5h first, as claude-hud picks it. */
|
|
21
|
+
export function limitResetAt(usage: UsageLimit): Date | null {
|
|
22
|
+
if (usage.fiveHour === 100) return usage.fiveHourResetAt;
|
|
23
|
+
if (usage.sevenDay === 100) return usage.sevenDayResetAt;
|
|
24
|
+
return usage.monthlyResetAt;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** The windows after 5h, in display order, with their compact labels. */
|
|
28
|
+
export function longWindows(usage: UsageLimit) {
|
|
29
|
+
return [
|
|
30
|
+
{ key: "label.weekly", short: "7d", percent: usage.sevenDay, resetAt: usage.sevenDayResetAt, windowMs: SEVEN_DAY_WINDOW_MS },
|
|
31
|
+
{ key: "label.monthly", short: "mo", percent: usage.monthly, resetAt: usage.monthlyResetAt, windowMs: MONTHLY_WINDOW_MS },
|
|
32
|
+
] as const;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* The long windows to show after 5h: each one at or above sevenDayThreshold. With no 5h window the first
|
|
37
|
+
* long window is always shown, as claude-hud's weekly-only form.
|
|
38
|
+
*/
|
|
39
|
+
export function shownLongWindows(usage: UsageLimit, sevenDayThreshold: number) {
|
|
40
|
+
const present = longWindows(usage).filter((w) => w.percent !== null);
|
|
41
|
+
return present.filter((w, i) => (usage.fiveHour === null && i === 0) || w.percent! >= sevenDayThreshold);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function formatUsagePercent(percent: number | null, colors?: Colors, mode: UsageValueMode = "percent"): string {
|
|
45
|
+
if (percent === null) return label("--", colors);
|
|
46
|
+
const color = getQuotaColor(percent, colors);
|
|
47
|
+
const displayPercent = mode === "remaining" ? Math.max(0, 100 - percent) : percent;
|
|
48
|
+
return `${color}${displayPercent}%${RESET}`;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Ported from claude-hud's render/lines/usage. Its label alignment is not ported (pi-hud-plus doesn't align labels). */
|
|
52
|
+
export function renderUsageLine({ snapshot, config, width }: RenderContext): string | null {
|
|
53
|
+
const { display, colors } = config;
|
|
54
|
+
const usage = snapshot.usageLimit;
|
|
55
|
+
if (!display.showUsage || !usage) return null;
|
|
56
|
+
|
|
57
|
+
const now = snapshot.now ?? Date.now();
|
|
58
|
+
const usageLabel = label(t("label.usage"), colors);
|
|
59
|
+
|
|
60
|
+
if (usage.balanceLabel) return `${usageLabel} ${usage.balanceLabel}`;
|
|
61
|
+
|
|
62
|
+
const { timeFormat, showResetLabel, usageCompact, usageValue: usageValueMode } = display;
|
|
63
|
+
const resetsKey = limitResetTimeFormat(timeFormat) === "absolute" ? "format.resets" : "format.resetsIn";
|
|
64
|
+
|
|
65
|
+
if (isLimitReached(usage)) {
|
|
66
|
+
const resetTime = formatResetTime(limitResetAt(usage), limitResetTimeFormat(timeFormat), now);
|
|
67
|
+
if (usageCompact) return critical(`⚠ Limit${resetTime ? ` (${resetTime})` : ""}`, colors);
|
|
68
|
+
const resetSuffix = resetTime ? (showResetLabel ? ` (${t(resetsKey)} ${resetTime})` : ` (${resetTime})`) : "";
|
|
69
|
+
return `${usageLabel} ${critical(`⚠ ${t("status.limitReached")}${resetSuffix}`, colors)}`;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const { fiveHour, sevenDay } = usage;
|
|
73
|
+
if (Math.max(fiveHour ?? 0, sevenDay ?? 0) < display.usageThreshold) return null;
|
|
74
|
+
|
|
75
|
+
const longParts = shownLongWindows(usage, display.sevenDayThreshold);
|
|
76
|
+
|
|
77
|
+
if (usageCompact) {
|
|
78
|
+
const parts = [
|
|
79
|
+
fiveHour !== null ? formatCompactWindowPart("5h", fiveHour, usage.fiveHourResetAt, FIVE_HOUR_WINDOW_MS, timeFormat, now, colors, usageValueMode) : null,
|
|
80
|
+
...longParts.map((w) => formatCompactWindowPart(w.short, w.percent, w.resetAt, w.windowMs, timeFormat, now, colors, usageValueMode)),
|
|
81
|
+
].filter((part) => part !== null);
|
|
82
|
+
return parts.length > 0 ? parts.join(" | ") : null;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const common = { colors, usageBarEnabled: display.usageBarEnabled, barWidth: barWidth(width), timeFormat, now, showResetLabel, usageValueMode };
|
|
86
|
+
const longPart = (w: (typeof longParts)[number]) =>
|
|
87
|
+
formatUsageWindowPart({ ...common, label: t(w.key), percent: w.percent, resetAt: w.resetAt, windowMs: w.windowMs, forceLabel: true });
|
|
88
|
+
|
|
89
|
+
// No 5h window but a long one: claude-hud's weekly-only form (or monthly-only).
|
|
90
|
+
if (fiveHour === null && longParts.length > 0) return `${usageLabel} ${longParts.map(longPart).join(" | ")}`;
|
|
91
|
+
|
|
92
|
+
const fiveHourPart = formatUsageWindowPart({ ...common, label: "5h", percent: fiveHour, resetAt: usage.fiveHourResetAt, windowMs: FIVE_HOUR_WINDOW_MS });
|
|
93
|
+
return [`${usageLabel} ${fiveHourPart}`, ...longParts.map(longPart)].join(" | ");
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function formatCompactWindowPart(
|
|
97
|
+
windowLabel: string,
|
|
98
|
+
percent: number | null,
|
|
99
|
+
resetAt: Date | null,
|
|
100
|
+
windowMs: number,
|
|
101
|
+
timeFormat: TimeFormatMode,
|
|
102
|
+
now: number,
|
|
103
|
+
colors?: Colors,
|
|
104
|
+
usageValueMode: UsageValueMode = "percent",
|
|
105
|
+
): string {
|
|
106
|
+
const usageDisplay = formatUsagePercent(percent, colors, usageValueMode);
|
|
107
|
+
const reset = formatWindowTime(resetAt, windowMs, timeFormat, now);
|
|
108
|
+
const styledLabel = label(`${windowLabel}:`, colors);
|
|
109
|
+
return reset ? `${styledLabel} ${usageDisplay} ${label(`(${reset})`, colors)}` : `${styledLabel} ${usageDisplay}`;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function formatUsageWindowPart({
|
|
113
|
+
label: windowLabel,
|
|
114
|
+
percent,
|
|
115
|
+
resetAt,
|
|
116
|
+
windowMs,
|
|
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
|
+
windowMs: number;
|
|
130
|
+
colors?: Colors;
|
|
131
|
+
usageBarEnabled: boolean;
|
|
132
|
+
barWidth: number;
|
|
133
|
+
timeFormat: TimeFormatMode;
|
|
134
|
+
now: number;
|
|
135
|
+
showResetLabel: boolean;
|
|
136
|
+
forceLabel?: boolean;
|
|
137
|
+
usageValueMode: UsageValueMode;
|
|
138
|
+
}): string {
|
|
139
|
+
const usageDisplay = formatUsagePercent(percent, colors, usageValueMode);
|
|
140
|
+
const reset = formatWindowTime(resetAt, windowMs, timeFormat, now);
|
|
141
|
+
const styledLabel = label(windowLabel, colors);
|
|
142
|
+
const showResetWording = timeFormat !== "elapsed" && timeFormat !== "elapsedAndAbsolute";
|
|
143
|
+
const resetsKey = timeFormat === "absolute" ? "format.resets" : "format.resetsIn";
|
|
144
|
+
|
|
145
|
+
const resetSuffix = reset ? (showResetLabel && showResetWording ? `(${t(resetsKey)} ${reset})` : `(${reset})`) : "";
|
|
146
|
+
|
|
147
|
+
if (usageBarEnabled) {
|
|
148
|
+
const bar = quotaBar(percent ?? 0, barWidth, colors);
|
|
149
|
+
const body = resetSuffix ? `${bar} ${usageDisplay} ${resetSuffix}` : `${bar} ${usageDisplay}`;
|
|
150
|
+
return forceLabel ? `${styledLabel} ${body}` : body;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
return resetSuffix ? `${styledLabel} ${usageDisplay} ${resetSuffix}` : `${styledLabel} ${usageDisplay}`;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function limitResetTimeFormat(timeFormat: TimeFormatMode): "relative" | "absolute" | "both" {
|
|
157
|
+
if (timeFormat === "elapsedAndAbsolute") return "absolute";
|
|
158
|
+
if (timeFormat === "elapsed") return "relative";
|
|
159
|
+
return timeFormat;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function formatWindowTime(resetAt: Date | null, windowMs: number, timeFormat: TimeFormatMode, now: number): string {
|
|
163
|
+
if (timeFormat === "elapsed") return formatElapsedWindow(resetAt, windowMs, now);
|
|
164
|
+
|
|
165
|
+
if (timeFormat === "elapsedAndAbsolute") {
|
|
166
|
+
const elapsed = formatElapsedWindow(resetAt, windowMs, now);
|
|
167
|
+
const absolute = formatResetTime(resetAt, "absolute", now);
|
|
168
|
+
return elapsed && absolute ? `${elapsed}, ${absolute}` : elapsed || absolute;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
return formatResetTime(resetAt, timeFormat, now);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function formatElapsedWindow(resetAt: Date | null, windowMs: number, now: number): string {
|
|
175
|
+
if (!resetAt) return "";
|
|
176
|
+
const windowStart = resetAt.getTime() - windowMs;
|
|
177
|
+
const elapsed = Math.max(0, Math.min(100, Math.round(((now - windowStart) / windowMs) * 100)));
|
|
178
|
+
return `${elapsed}% elapsed`;
|
|
179
|
+
}
|