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/config.ts
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
import * as fs from "node:fs";
|
|
2
2
|
import * as path from "node:path";
|
|
3
|
+
import { createDebug } from "./debug.ts";
|
|
3
4
|
import type { Language } from "./i18n/types.ts";
|
|
4
5
|
|
|
5
6
|
export type LineLayoutType = "compact" | "expanded";
|
|
6
7
|
export type ContextValueMode = "percent" | "tokens" | "remaining" | "both";
|
|
8
|
+
export type UsageValueMode = "percent" | "remaining";
|
|
7
9
|
export type GitBranchOverflowMode = "truncate" | "wrap";
|
|
8
10
|
|
|
9
11
|
/**
|
|
@@ -16,7 +18,7 @@ export type GitBranchOverflowMode = "truncate" | "wrap";
|
|
|
16
18
|
export type ModelFormatMode = "full" | "compact" | "short";
|
|
17
19
|
export type TimeFormatMode = "relative" | "absolute" | "both" | "elapsed" | "elapsedAndAbsolute";
|
|
18
20
|
export type CustomLinePosition = "first" | "last";
|
|
19
|
-
export type HudElement = "project" | "context" | "promptCache" | "memory" | "environment" | "tools" | "sessionTime";
|
|
21
|
+
export type HudElement = "project" | "context" | "usage" | "promptCache" | "memory" | "environment" | "tools" | "sessionTime";
|
|
20
22
|
|
|
21
23
|
export type HudColorName =
|
|
22
24
|
| "dim"
|
|
@@ -33,7 +35,9 @@ export type HudColorValue = HudColorName | number | string;
|
|
|
33
35
|
|
|
34
36
|
export interface HudColorOverrides {
|
|
35
37
|
context: HudColorValue;
|
|
38
|
+
usage: HudColorValue;
|
|
36
39
|
warning: HudColorValue;
|
|
40
|
+
usageWarning: HudColorValue;
|
|
37
41
|
critical: HudColorValue;
|
|
38
42
|
model: HudColorValue;
|
|
39
43
|
project: HudColorValue;
|
|
@@ -48,6 +52,7 @@ export interface HudColorOverrides {
|
|
|
48
52
|
export const DEFAULT_ELEMENT_ORDER: HudElement[] = [
|
|
49
53
|
"project",
|
|
50
54
|
"context",
|
|
55
|
+
"usage",
|
|
51
56
|
"promptCache",
|
|
52
57
|
"memory",
|
|
53
58
|
"environment",
|
|
@@ -55,6 +60,8 @@ export const DEFAULT_ELEMENT_ORDER: HudElement[] = [
|
|
|
55
60
|
"sessionTime",
|
|
56
61
|
];
|
|
57
62
|
|
|
63
|
+
export const DEFAULT_MERGE_GROUPS: HudElement[][] = [["context", "usage"]];
|
|
64
|
+
|
|
58
65
|
const KNOWN_ELEMENTS = new Set<HudElement>(DEFAULT_ELEMENT_ORDER);
|
|
59
66
|
|
|
60
67
|
export interface HudConfig {
|
|
@@ -63,7 +70,7 @@ export interface HudConfig {
|
|
|
63
70
|
showSeparators: boolean;
|
|
64
71
|
pathLevels: 1 | 2 | 3;
|
|
65
72
|
elementOrder: HudElement[];
|
|
66
|
-
/** Shell command whose output is shown as an Extra command Line. "" = off.
|
|
73
|
+
/** Shell command whose output is shown as an Extra command Line. "" = off. */
|
|
67
74
|
extraCommand: string;
|
|
68
75
|
gitStatus: {
|
|
69
76
|
enabled: boolean;
|
|
@@ -84,6 +91,11 @@ export interface HudConfig {
|
|
|
84
91
|
showDuration: boolean;
|
|
85
92
|
showSpeed: boolean;
|
|
86
93
|
showTokenBreakdown: boolean;
|
|
94
|
+
showUsage: boolean;
|
|
95
|
+
usageValue: UsageValueMode;
|
|
96
|
+
usageBarEnabled: boolean;
|
|
97
|
+
showResetLabel: boolean;
|
|
98
|
+
usageCompact: boolean;
|
|
87
99
|
showTools: boolean;
|
|
88
100
|
toolNameMaxLength: number;
|
|
89
101
|
toolsMaxVisible: number;
|
|
@@ -100,7 +112,13 @@ export interface HudConfig {
|
|
|
100
112
|
mergeGroups: HudElement[][];
|
|
101
113
|
contextWarningThreshold: number;
|
|
102
114
|
contextCriticalThreshold: number;
|
|
115
|
+
usageThreshold: number;
|
|
116
|
+
/** Shows the Weekly part at or above this % used; it gates the Monthly part too. */
|
|
117
|
+
sevenDayThreshold: number;
|
|
103
118
|
environmentThreshold: number;
|
|
119
|
+
/** The External usage snapshot file. "" = off. */
|
|
120
|
+
externalUsagePath: string;
|
|
121
|
+
externalUsageFreshnessMs: number;
|
|
104
122
|
modelFormat: ModelFormatMode;
|
|
105
123
|
modelOverride: string;
|
|
106
124
|
customLine: string;
|
|
@@ -136,6 +154,11 @@ export const DEFAULT_CONFIG: HudConfig = {
|
|
|
136
154
|
showDuration: false,
|
|
137
155
|
showSpeed: false,
|
|
138
156
|
showTokenBreakdown: true,
|
|
157
|
+
showUsage: true,
|
|
158
|
+
usageValue: "percent",
|
|
159
|
+
usageBarEnabled: true,
|
|
160
|
+
showResetLabel: true,
|
|
161
|
+
usageCompact: false,
|
|
139
162
|
showTools: false,
|
|
140
163
|
toolNameMaxLength: 0,
|
|
141
164
|
toolsMaxVisible: 4,
|
|
@@ -149,10 +172,14 @@ export const DEFAULT_CONFIG: HudConfig = {
|
|
|
149
172
|
showSessionStartDate: false,
|
|
150
173
|
showLastResponseAt: false,
|
|
151
174
|
showExtensionStatuses: true,
|
|
152
|
-
mergeGroups: [],
|
|
175
|
+
mergeGroups: DEFAULT_MERGE_GROUPS.map((group) => [...group]),
|
|
153
176
|
contextWarningThreshold: 70,
|
|
154
177
|
contextCriticalThreshold: 85,
|
|
178
|
+
usageThreshold: 0,
|
|
179
|
+
sevenDayThreshold: 80,
|
|
155
180
|
environmentThreshold: 0,
|
|
181
|
+
externalUsagePath: "",
|
|
182
|
+
externalUsageFreshnessMs: 300000,
|
|
156
183
|
modelFormat: "full",
|
|
157
184
|
modelOverride: "",
|
|
158
185
|
customLine: "",
|
|
@@ -161,7 +188,9 @@ export const DEFAULT_CONFIG: HudConfig = {
|
|
|
161
188
|
},
|
|
162
189
|
colors: {
|
|
163
190
|
context: "green",
|
|
191
|
+
usage: "brightBlue",
|
|
164
192
|
warning: "yellow",
|
|
193
|
+
usageWarning: "brightMagenta",
|
|
165
194
|
critical: "red",
|
|
166
195
|
model: "cyan",
|
|
167
196
|
project: "yellow",
|
|
@@ -174,9 +203,9 @@ export const DEFAULT_CONFIG: HudConfig = {
|
|
|
174
203
|
},
|
|
175
204
|
};
|
|
176
205
|
|
|
177
|
-
type Raw = Record<string, unknown>;
|
|
206
|
+
export type Raw = Record<string, unknown>;
|
|
178
207
|
|
|
179
|
-
function isObject(value: unknown): value is Raw {
|
|
208
|
+
export function isObject(value: unknown): value is Raw {
|
|
180
209
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
181
210
|
}
|
|
182
211
|
|
|
@@ -217,9 +246,9 @@ function validateElementOrder(value: unknown): HudElement[] {
|
|
|
217
246
|
return elementOrder.length > 0 ? elementOrder : [...DEFAULT_ELEMENT_ORDER];
|
|
218
247
|
}
|
|
219
248
|
|
|
220
|
-
// claude-hud falls back to its default group when nothing valid survives; our default is [] so every invalid case is [].
|
|
221
249
|
function validateMergeGroups(value: unknown): HudElement[][] {
|
|
222
|
-
if (!Array.isArray(value)) return [];
|
|
250
|
+
if (!Array.isArray(value)) return DEFAULT_MERGE_GROUPS.map((group) => [...group]);
|
|
251
|
+
if (value.length === 0) return [];
|
|
223
252
|
|
|
224
253
|
const usedElements = new Set<HudElement>();
|
|
225
254
|
const mergeGroups: HudElement[][] = [];
|
|
@@ -235,7 +264,7 @@ function validateMergeGroups(value: unknown): HudElement[][] {
|
|
|
235
264
|
}
|
|
236
265
|
}
|
|
237
266
|
|
|
238
|
-
return mergeGroups;
|
|
267
|
+
return mergeGroups.length > 0 ? mergeGroups : DEFAULT_MERGE_GROUPS.map((group) => [...group]);
|
|
239
268
|
}
|
|
240
269
|
|
|
241
270
|
function validateThreshold(value: unknown, max = 100): number {
|
|
@@ -263,6 +292,11 @@ function validateNonNegativeInteger(value: unknown, fallback: number): number {
|
|
|
263
292
|
return value;
|
|
264
293
|
}
|
|
265
294
|
|
|
295
|
+
function validateFreshnessMs(value: unknown): number {
|
|
296
|
+
if (typeof value !== "number" || !Number.isFinite(value)) return DEFAULT_CONFIG.display.externalUsageFreshnessMs;
|
|
297
|
+
return Math.max(0, Math.floor(value));
|
|
298
|
+
}
|
|
299
|
+
|
|
266
300
|
function truncatedString(value: unknown, fallback: string): string {
|
|
267
301
|
return typeof value === "string" ? value.slice(0, 80) : fallback;
|
|
268
302
|
}
|
|
@@ -307,6 +341,11 @@ export function mergeConfig(userConfig: unknown): HudConfig {
|
|
|
307
341
|
showDuration: displayBool("showDuration"),
|
|
308
342
|
showSpeed: displayBool("showSpeed"),
|
|
309
343
|
showTokenBreakdown: displayBool("showTokenBreakdown"),
|
|
344
|
+
showUsage: displayBool("showUsage"),
|
|
345
|
+
usageValue: oneOf(display.usageValue, ["percent", "remaining"] as const, D.display.usageValue),
|
|
346
|
+
usageBarEnabled: displayBool("usageBarEnabled"),
|
|
347
|
+
showResetLabel: displayBool("showResetLabel"),
|
|
348
|
+
usageCompact: displayBool("usageCompact"),
|
|
310
349
|
showTools: displayBool("showTools"),
|
|
311
350
|
toolNameMaxLength: validateNonNegativeInteger(display.toolNameMaxLength, D.display.toolNameMaxLength),
|
|
312
351
|
toolsMaxVisible: validateNonNegativeInteger(display.toolsMaxVisible, D.display.toolsMaxVisible),
|
|
@@ -323,7 +362,12 @@ export function mergeConfig(userConfig: unknown): HudConfig {
|
|
|
323
362
|
mergeGroups: validateMergeGroups(display.mergeGroups),
|
|
324
363
|
contextWarningThreshold: validateContextThreshold(display.contextWarningThreshold, D.display.contextWarningThreshold),
|
|
325
364
|
contextCriticalThreshold: validateContextThreshold(display.contextCriticalThreshold, D.display.contextCriticalThreshold),
|
|
365
|
+
usageThreshold: validateThreshold(display.usageThreshold, 100),
|
|
366
|
+
// claude-hud's validateThreshold turns an absent key into 0 too, against its documented default of 80.
|
|
367
|
+
sevenDayThreshold: display.sevenDayThreshold === undefined ? D.display.sevenDayThreshold : validateThreshold(display.sevenDayThreshold, 100),
|
|
326
368
|
environmentThreshold: validateThreshold(display.environmentThreshold, 100),
|
|
369
|
+
externalUsagePath: typeof display.externalUsagePath === "string" ? display.externalUsagePath.trim() : "",
|
|
370
|
+
externalUsageFreshnessMs: validateFreshnessMs(display.externalUsageFreshnessMs),
|
|
327
371
|
modelFormat: oneOf(display.modelFormat, ["full", "compact", "short"] as const, D.display.modelFormat),
|
|
328
372
|
modelOverride: truncatedString(display.modelOverride, D.display.modelOverride),
|
|
329
373
|
customLine: truncatedString(display.customLine, D.display.customLine),
|
|
@@ -336,7 +380,9 @@ export function mergeConfig(userConfig: unknown): HudConfig {
|
|
|
336
380
|
},
|
|
337
381
|
colors: {
|
|
338
382
|
context: color("context"),
|
|
383
|
+
usage: color("usage"),
|
|
339
384
|
warning: color("warning"),
|
|
385
|
+
usageWarning: color("usageWarning"),
|
|
340
386
|
critical: color("critical"),
|
|
341
387
|
model: color("model"),
|
|
342
388
|
project: color("project"),
|
|
@@ -351,7 +397,7 @@ export function mergeConfig(userConfig: unknown): HudConfig {
|
|
|
351
397
|
}
|
|
352
398
|
|
|
353
399
|
/** Objects merge recursively; arrays and scalars from `override` replace. */
|
|
354
|
-
function deepMerge(base: Raw, override: Raw): Raw {
|
|
400
|
+
export function deepMerge(base: Raw, override: Raw): Raw {
|
|
355
401
|
const merged: Raw = { ...base };
|
|
356
402
|
for (const [key, value] of Object.entries(override)) {
|
|
357
403
|
const current = merged[key];
|
|
@@ -360,20 +406,22 @@ function deepMerge(base: Raw, override: Raw): Raw {
|
|
|
360
406
|
return merged;
|
|
361
407
|
}
|
|
362
408
|
|
|
409
|
+
const debug = createDebug("config");
|
|
410
|
+
|
|
363
411
|
/** Missing, unreadable, unparseable or non-object files count as empty so the HUD still renders. */
|
|
364
412
|
function readJsonObject(file: string): Raw {
|
|
365
413
|
try {
|
|
366
414
|
const parsed: unknown = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
367
|
-
|
|
368
|
-
|
|
415
|
+
if (isObject(parsed)) return parsed;
|
|
416
|
+
debug(`Ignoring ${file}: not a JSON object`);
|
|
417
|
+
return {};
|
|
418
|
+
} catch (error) {
|
|
419
|
+
if ((error as NodeJS.ErrnoException).code !== "ENOENT") debug(`Failed to read ${file}:`, error);
|
|
369
420
|
return {};
|
|
370
421
|
}
|
|
371
422
|
}
|
|
372
423
|
|
|
373
|
-
/** Reads `<agentDir>/pi-hud-plus.json`,
|
|
374
|
-
export function loadConfig(
|
|
375
|
-
|
|
376
|
-
// A cloned repo must not run shell commands just by being opened.
|
|
377
|
-
const { extraCommand: _ignored, ...project } = readJsonObject(path.join(cwd, ".pi", "pi-hud-plus.json"));
|
|
378
|
-
return mergeConfig(deepMerge(global, project));
|
|
424
|
+
/** Reads `<agentDir>/pi-hud-plus.json`, the only config file (see docs/adr/0001-global-config-only.md). */
|
|
425
|
+
export function loadConfig(agentDir: string): HudConfig {
|
|
426
|
+
return mergeConfig(readJsonObject(path.join(agentDir, "pi-hud-plus.json")));
|
|
379
427
|
}
|
package/src/debug.ts
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
// Ported from claude-hud src/debug.ts. pi owns the terminal, so lines go to a file in pi's agent dir instead of stderr.
|
|
2
|
+
import { appendFileSync } from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { format } from "node:util";
|
|
5
|
+
import { getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* A namespaced logger, enabled by DEBUG=pi-hud-plus or DEBUG=*.
|
|
9
|
+
* Writes to ~/.pi/agent/pi-hud-plus-debug.log.
|
|
10
|
+
*/
|
|
11
|
+
export function createDebug(namespace: string) {
|
|
12
|
+
return function debug(msg: string, ...args: unknown[]): void {
|
|
13
|
+
const env = process.env.DEBUG;
|
|
14
|
+
if (!env?.includes("pi-hud-plus") && env !== "*") return;
|
|
15
|
+
try {
|
|
16
|
+
appendFileSync(path.join(getAgentDir(), "pi-hud-plus-debug.log"), `${new Date().toISOString()} [pi-hud-plus:${namespace}] ${format(msg, ...args)}\n`, { mode: 0o600 });
|
|
17
|
+
} catch {
|
|
18
|
+
// Logging must never break the HUD
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import type { HudConfig } from "./config.ts";
|
|
3
|
+
import { sanitize } from "./sanitize.ts";
|
|
4
|
+
import type { UsageLimit } from "./types.ts";
|
|
5
|
+
|
|
6
|
+
/** Ported from claude-hud's external-usage (read side). The file another tool writes, in claude-hud's format. */
|
|
7
|
+
interface ExternalUsageSnapshot {
|
|
8
|
+
five_hour?: { used_percentage?: unknown; resets_at?: unknown } | null;
|
|
9
|
+
seven_day?: { used_percentage?: unknown; resets_at?: unknown } | null;
|
|
10
|
+
updated_at?: unknown;
|
|
11
|
+
balance_label?: unknown;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
const MAX_BALANCE_LABEL_LENGTH = 50;
|
|
15
|
+
|
|
16
|
+
/** A UsageLimit with every Limit window null; a fresh object, so callers can fill it in. */
|
|
17
|
+
export const emptyUsageLimit = (): UsageLimit => ({ fiveHour: null, sevenDay: null, monthly: null, fiveHourResetAt: null, sevenDayResetAt: null, monthlyResetAt: null });
|
|
18
|
+
|
|
19
|
+
/** A percent rounded and clamped to 0-100; null unless a finite number. */
|
|
20
|
+
export function parseUsagePercent(value: unknown): number | null {
|
|
21
|
+
if (typeof value !== "number" || !Number.isFinite(value)) return null;
|
|
22
|
+
return Math.round(Math.min(100, Math.max(0, value)));
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** claude-hud's balance_label sanitising: escape sequences out, then control and bidi characters, cut to 50. */
|
|
26
|
+
export function sanitizeBalanceLabel(value: unknown): string | null {
|
|
27
|
+
if (typeof value !== "string") return null;
|
|
28
|
+
const sanitized = sanitize(
|
|
29
|
+
value
|
|
30
|
+
.replace(/\x1B\[[0-?]*[ -/]*[@-~]/g, "")
|
|
31
|
+
.replace(/\x1B\][^\x07\x1B]*(?:\x07|\x1B\\)/g, "")
|
|
32
|
+
.replace(/\x1B[@-Z\\-_]/g, ""),
|
|
33
|
+
).trim();
|
|
34
|
+
if (!sanitized) return null;
|
|
35
|
+
return sanitized.length <= MAX_BALANCE_LABEL_LENGTH ? sanitized : `${sanitized.slice(0, MAX_BALANCE_LABEL_LENGTH - 3)}...`;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** A number above 1e12 is epoch ms, otherwise epoch seconds; strings go through Date. */
|
|
39
|
+
function parseDateValue(value: unknown): Date | null {
|
|
40
|
+
if (typeof value === "number") {
|
|
41
|
+
if (!Number.isFinite(value) || value <= 0) return null;
|
|
42
|
+
const date = new Date(value > 1e12 ? value : value * 1000);
|
|
43
|
+
return Number.isNaN(date.getTime()) ? null : date;
|
|
44
|
+
}
|
|
45
|
+
if (typeof value === "string" && value.trim()) {
|
|
46
|
+
const date = new Date(value);
|
|
47
|
+
return Number.isNaN(date.getTime()) ? null : date;
|
|
48
|
+
}
|
|
49
|
+
return null;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** The External usage snapshot at `display.externalUsagePath`, or null when off, missing, stale or malformed. A small sync read. */
|
|
53
|
+
export function getUsageFromExternalSnapshot(config: HudConfig, now = Date.now()): UsageLimit | null {
|
|
54
|
+
const snapshotPath = config.display.externalUsagePath;
|
|
55
|
+
if (!snapshotPath) return null;
|
|
56
|
+
|
|
57
|
+
try {
|
|
58
|
+
const parsed = JSON.parse(fs.readFileSync(snapshotPath, "utf8")) as ExternalUsageSnapshot;
|
|
59
|
+
const updatedAt = parseDateValue(parsed.updated_at)?.getTime();
|
|
60
|
+
if (updatedAt === undefined || now - updatedAt > config.display.externalUsageFreshnessMs) return null;
|
|
61
|
+
|
|
62
|
+
const fiveHour = parseUsagePercent(parsed.five_hour?.used_percentage);
|
|
63
|
+
const sevenDay = parseUsagePercent(parsed.seven_day?.used_percentage);
|
|
64
|
+
const balanceLabel = sanitizeBalanceLabel(parsed.balance_label);
|
|
65
|
+
if (fiveHour === null && sevenDay === null && balanceLabel === null) return null;
|
|
66
|
+
|
|
67
|
+
const fiveHourResetAt = parseDateValue(parsed.five_hour?.resets_at);
|
|
68
|
+
const sevenDayResetAt = parseDateValue(parsed.seven_day?.resets_at);
|
|
69
|
+
// An unparseable reset rejects the whole snapshot, as in claude-hud.
|
|
70
|
+
if (parsed.five_hour && parsed.five_hour.resets_at != null && fiveHourResetAt === null) return null;
|
|
71
|
+
if (parsed.seven_day && parsed.seven_day.resets_at != null && sevenDayResetAt === null) return null;
|
|
72
|
+
|
|
73
|
+
const usage: UsageLimit = { ...emptyUsageLimit(), fiveHour, sevenDay, fiveHourResetAt, sevenDayResetAt };
|
|
74
|
+
if (balanceLabel !== null) usage.balanceLabel = balanceLabel;
|
|
75
|
+
return usage;
|
|
76
|
+
} catch {
|
|
77
|
+
return null;
|
|
78
|
+
}
|
|
79
|
+
}
|
package/src/extra-cmd.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
// Ported from claude-hud src/extra-cmd.ts. Changes for pi: the command comes from config (no --extra-cmd
|
|
2
|
-
// argv parsing) and runs through pi.exec as `sh -c`, since pi.exec doesn't use a shell.
|
|
2
|
+
// argv parsing) and runs through pi.exec as `sh -c`, since pi.exec doesn't use a shell.
|
|
3
|
+
import { createDebug } from "./debug.ts";
|
|
3
4
|
import type { Exec } from "./git.ts";
|
|
4
5
|
import { sanitize as stripControls } from "./sanitize.ts";
|
|
5
6
|
|
|
@@ -7,6 +8,9 @@ const MAX_BUFFER = 10 * 1024; // 10KB - plenty for a label
|
|
|
7
8
|
const MAX_LABEL_LENGTH = 50;
|
|
8
9
|
const TIMEOUT_MS = 3000;
|
|
9
10
|
|
|
11
|
+
// Messages never include the command or its output: either may hold secrets.
|
|
12
|
+
const debug = createDebug("extra-cmd");
|
|
13
|
+
|
|
10
14
|
/**
|
|
11
15
|
* Sanitize output to prevent terminal escape injection.
|
|
12
16
|
* Strips whole ANSI/OSC escape sequences (so their parameters don't show), then control and bidi characters.
|
|
@@ -24,14 +28,27 @@ export function sanitize(input: string): string {
|
|
|
24
28
|
* Run the Extra command and parse its JSON output, expecting { label: string }.
|
|
25
29
|
* Returns null on any error (timeout, non-zero exit, parse failure, missing label).
|
|
26
30
|
*
|
|
27
|
-
* SECURITY NOTE: cmd comes only from the user's global config;
|
|
28
|
-
*
|
|
31
|
+
* SECURITY NOTE: cmd comes only from the user's global config; project config files aren't read
|
|
32
|
+
* (see loadConfig), so opening a repo can't run commands.
|
|
29
33
|
*/
|
|
30
34
|
export async function runExtraCmd(exec: Exec, cmd: string, timeout: number = TIMEOUT_MS): Promise<string | null> {
|
|
31
35
|
try {
|
|
32
36
|
const { stdout, code, killed } = await exec("sh", ["-c", cmd], { timeout, maxBuffer: MAX_BUFFER });
|
|
33
|
-
if (
|
|
34
|
-
|
|
37
|
+
if (killed) {
|
|
38
|
+
debug(`Command timed out after ${timeout}ms`);
|
|
39
|
+
return null;
|
|
40
|
+
}
|
|
41
|
+
if (code !== 0) {
|
|
42
|
+
debug(`Command failed with exit code ${code}`);
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
let data: unknown;
|
|
46
|
+
try {
|
|
47
|
+
data = JSON.parse(stdout.trim());
|
|
48
|
+
} catch {
|
|
49
|
+
debug("Failed to parse JSON output");
|
|
50
|
+
return null;
|
|
51
|
+
}
|
|
35
52
|
if (typeof data === "object" && data !== null && "label" in data && typeof data.label === "string") {
|
|
36
53
|
let label = sanitize(data.label);
|
|
37
54
|
if (label.length > MAX_LABEL_LENGTH) {
|
|
@@ -39,8 +56,10 @@ export async function runExtraCmd(exec: Exec, cmd: string, timeout: number = TIM
|
|
|
39
56
|
}
|
|
40
57
|
return label;
|
|
41
58
|
}
|
|
59
|
+
debug(`Command output missing 'label' field or invalid type`);
|
|
42
60
|
return null;
|
|
43
61
|
} catch {
|
|
62
|
+
debug("Command failed to run");
|
|
44
63
|
return null;
|
|
45
64
|
}
|
|
46
65
|
}
|
package/src/git.ts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
// Ported from claude-hud src/git.ts. Changes for pi: commands go through pi.exec (which resolves with an
|
|
2
2
|
// exit code instead of rejecting), every command passes --no-optional-locks, diff and rev-list are gated
|
|
3
|
-
// by config,
|
|
3
|
+
// by config, the branch (rev-parse) comes from pi's footerData, and branchUrl becomes githubUrl (the branch isn't known here).
|
|
4
|
+
import { stat } from "node:fs/promises";
|
|
5
|
+
import path from "node:path";
|
|
4
6
|
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
5
7
|
|
|
6
8
|
export type Exec = ExtensionAPI["exec"];
|
|
@@ -23,6 +25,8 @@ export interface FileStats {
|
|
|
23
25
|
deleted: number;
|
|
24
26
|
untracked: number;
|
|
25
27
|
trackedFiles: TrackedFile[];
|
|
28
|
+
/** The repo root that trackedFiles' paths are relative to; set when showFileStats collected them. */
|
|
29
|
+
root?: string;
|
|
26
30
|
}
|
|
27
31
|
|
|
28
32
|
export interface GitStatus {
|
|
@@ -32,11 +36,15 @@ export interface GitStatus {
|
|
|
32
36
|
behind: number;
|
|
33
37
|
fileStats?: FileStats;
|
|
34
38
|
lineDiff?: LineDiff;
|
|
39
|
+
/** The GitHub origin's https URL, for linking the branch. */
|
|
40
|
+
githubUrl?: string;
|
|
35
41
|
}
|
|
36
42
|
|
|
37
43
|
export interface GitStatusOptions {
|
|
38
44
|
showAheadBehind: boolean;
|
|
39
45
|
showFileStats: boolean;
|
|
46
|
+
/** Look up the GitHub origin for the branch link (expanded layout only). */
|
|
47
|
+
linkBranch: boolean;
|
|
40
48
|
}
|
|
41
49
|
|
|
42
50
|
/** Runs `git --no-optional-locks <args>`, rejecting like execFile on a non-zero exit or timeout. */
|
|
@@ -75,6 +83,15 @@ export async function getGitStatus(exec: Exec, cwd: string, options: GitStatusOp
|
|
|
75
83
|
} catch {
|
|
76
84
|
// Ignore errors
|
|
77
85
|
}
|
|
86
|
+
// claude-hud sorts at render time; here it runs once per git job instead of every frame.
|
|
87
|
+
if (fileStats) {
|
|
88
|
+
try {
|
|
89
|
+
fileStats.root = (await git(exec, cwd, ['rev-parse', '--show-toplevel'], 1000)).trim();
|
|
90
|
+
await sortByMtime(fileStats.trackedFiles, fileStats.root);
|
|
91
|
+
} catch {
|
|
92
|
+
// Keep git's order
|
|
93
|
+
}
|
|
94
|
+
}
|
|
78
95
|
}
|
|
79
96
|
|
|
80
97
|
// Get ahead/behind counts
|
|
@@ -93,7 +110,19 @@ export async function getGitStatus(exec: Exec, cwd: string, options: GitStatusOp
|
|
|
93
110
|
}
|
|
94
111
|
}
|
|
95
112
|
|
|
96
|
-
|
|
113
|
+
let githubUrl: string | undefined;
|
|
114
|
+
if (options.linkBranch) try {
|
|
115
|
+
const httpsBase = (await git(exec, cwd, ['remote', 'get-url', 'origin'], 1000))
|
|
116
|
+
.trim()
|
|
117
|
+
.replace(/^git@github\.com:/, 'https://github.com/')
|
|
118
|
+
.replace(/^ssh:\/\/git@github\.com\//, 'https://github.com/')
|
|
119
|
+
.replace(/\.git$/, '');
|
|
120
|
+
if (httpsBase.startsWith('https://github.com/')) githubUrl = httpsBase;
|
|
121
|
+
} catch {
|
|
122
|
+
// No remote or not GitHub
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
return { isDirty, ahead, behind, fileStats, lineDiff, githubUrl };
|
|
97
126
|
}
|
|
98
127
|
|
|
99
128
|
/**
|
|
@@ -203,6 +232,13 @@ function parseNumstat(numstatOutput: string, trackedPaths: Set<string>): { total
|
|
|
203
232
|
return { totalDiff, perFileDiff };
|
|
204
233
|
}
|
|
205
234
|
|
|
235
|
+
/** Newest-modified first; files that can't be stat'd (deleted) go last. */
|
|
236
|
+
async function sortByMtime(files: TrackedFile[], root: string): Promise<void> {
|
|
237
|
+
const mtimes = new Map(await Promise.all(files.map(async (file) =>
|
|
238
|
+
[file, await stat(path.resolve(root, file.fullPath)).then((s) => s.mtimeMs, () => 0)] as const)));
|
|
239
|
+
files.sort((a, b) => mtimes.get(b)! - mtimes.get(a)!);
|
|
240
|
+
}
|
|
241
|
+
|
|
206
242
|
function applyLineDiffsToFiles(files: TrackedFile[], perFileDiff: Map<string, LineDiff>): void {
|
|
207
243
|
for (const file of files) {
|
|
208
244
|
const diff = perFileDiff.get(file.fullPath);
|
package/src/i18n/en.ts
CHANGED
|
@@ -3,6 +3,9 @@ import type { Messages } from "./types.ts";
|
|
|
3
3
|
export const en: Messages = {
|
|
4
4
|
// Labels
|
|
5
5
|
"label.context": "Context",
|
|
6
|
+
"label.usage": "Usage",
|
|
7
|
+
"label.weekly": "Weekly",
|
|
8
|
+
"label.monthly": "Monthly",
|
|
6
9
|
"label.approxRam": "Approx RAM",
|
|
7
10
|
"label.promptCache": "Cache",
|
|
8
11
|
"label.estimatedCost": "Est.",
|
|
@@ -15,8 +18,11 @@ export const en: Messages = {
|
|
|
15
18
|
|
|
16
19
|
// Status
|
|
17
20
|
"status.expired": "expired",
|
|
21
|
+
"status.limitReached": "Limit reached",
|
|
18
22
|
|
|
19
23
|
// Format
|
|
24
|
+
"format.resets": "resets",
|
|
25
|
+
"format.resetsIn": "resets in",
|
|
20
26
|
"format.at": "at",
|
|
21
27
|
"format.in": "in",
|
|
22
28
|
"format.cache": "cache",
|
package/src/i18n/types.ts
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
export type MessageKey =
|
|
2
2
|
// Labels
|
|
3
3
|
| "label.context"
|
|
4
|
+
| "label.usage"
|
|
5
|
+
| "label.weekly"
|
|
6
|
+
| "label.monthly"
|
|
4
7
|
| "label.approxRam"
|
|
5
8
|
| "label.promptCache"
|
|
6
9
|
| "label.estimatedCost"
|
|
@@ -12,7 +15,10 @@ export type MessageKey =
|
|
|
12
15
|
| "label.prompts"
|
|
13
16
|
// Status
|
|
14
17
|
| "status.expired"
|
|
18
|
+
| "status.limitReached"
|
|
15
19
|
// Format
|
|
20
|
+
| "format.resets"
|
|
21
|
+
| "format.resetsIn"
|
|
16
22
|
| "format.at"
|
|
17
23
|
| "format.in"
|
|
18
24
|
| "format.cache"
|
package/src/i18n/zh-Hans.ts
CHANGED
|
@@ -3,6 +3,9 @@ import type { Messages } from "./types.ts";
|
|
|
3
3
|
export const zhHans: Messages = {
|
|
4
4
|
// Labels
|
|
5
5
|
"label.context": "上下文",
|
|
6
|
+
"label.usage": "用量",
|
|
7
|
+
"label.weekly": "本周",
|
|
8
|
+
"label.monthly": "本月",
|
|
6
9
|
"label.approxRam": "内存",
|
|
7
10
|
"label.promptCache": "缓存",
|
|
8
11
|
"label.estimatedCost": "估算",
|
|
@@ -15,8 +18,11 @@ export const zhHans: Messages = {
|
|
|
15
18
|
|
|
16
19
|
// Status
|
|
17
20
|
"status.expired": "已过期",
|
|
21
|
+
"status.limitReached": "已达上限",
|
|
18
22
|
|
|
19
23
|
// Format
|
|
24
|
+
"format.resets": "重置于",
|
|
25
|
+
"format.resetsIn": "重置剩余",
|
|
20
26
|
"format.at": "",
|
|
21
27
|
"format.in": "输入",
|
|
22
28
|
"format.cache": "缓存",
|