pi-hud-plus 0.0.0-stage → 0.2.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 +21 -0
- package/LICENSE +22 -0
- package/README.md +211 -2
- package/package.json +47 -4
- package/src/clock.ts +14 -0
- package/src/commands.ts +213 -0
- package/src/config.ts +376 -0
- package/src/extra-cmd.ts +46 -0
- package/src/git.ts +213 -0
- package/src/i18n/en.ts +28 -0
- package/src/i18n/index.ts +38 -0
- package/src/i18n/types.ts +27 -0
- package/src/i18n/zh-Hans.ts +28 -0
- package/src/index.ts +420 -0
- package/src/memory.ts +116 -0
- package/src/render/colors.ts +168 -0
- package/src/render/index.ts +177 -0
- package/src/render/lines/context.ts +46 -0
- package/src/render/lines/environment.ts +21 -0
- package/src/render/lines/git.ts +70 -0
- package/src/render/lines/memory.ts +17 -0
- package/src/render/lines/project.ts +79 -0
- package/src/render/lines/prompt-cache.ts +40 -0
- package/src/render/lines/session-stats.ts +58 -0
- package/src/render/lines/session-time.ts +73 -0
- package/src/render/session-line.ts +42 -0
- package/src/render/tools-line.ts +51 -0
- package/src/sanitize.ts +7 -0
- package/src/session.ts +57 -0
- package/src/speed-tracker.ts +32 -0
- package/src/types.ts +90 -0
package/src/config.ts
ADDED
|
@@ -0,0 +1,376 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import * as path from "node:path";
|
|
3
|
+
import type { Language } from "./i18n/types.ts";
|
|
4
|
+
|
|
5
|
+
export type LineLayoutType = "compact" | "expanded";
|
|
6
|
+
export type ContextValueMode = "percent" | "tokens" | "remaining" | "both";
|
|
7
|
+
export type GitBranchOverflowMode = "truncate" | "wrap";
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Controls how the model name is displayed in the HUD badge.
|
|
11
|
+
*
|
|
12
|
+
* full: Show the raw display name as-is (e.g. "Opus 4.6 (1M context)")
|
|
13
|
+
* compact: Strip redundant context-window suffix (e.g. "Opus 4.6")
|
|
14
|
+
* short: Strip context suffix AND "Claude " prefix (e.g. "Opus 4.6")
|
|
15
|
+
*/
|
|
16
|
+
export type ModelFormatMode = "full" | "compact" | "short";
|
|
17
|
+
export type TimeFormatMode = "relative" | "absolute" | "both" | "elapsed" | "elapsedAndAbsolute";
|
|
18
|
+
export type CustomLinePosition = "first" | "last";
|
|
19
|
+
export type HudElement = "project" | "context" | "promptCache" | "memory" | "environment" | "tools" | "sessionTime";
|
|
20
|
+
|
|
21
|
+
export type HudColorName =
|
|
22
|
+
| "dim"
|
|
23
|
+
| "red"
|
|
24
|
+
| "green"
|
|
25
|
+
| "yellow"
|
|
26
|
+
| "magenta"
|
|
27
|
+
| "cyan"
|
|
28
|
+
| "brightBlue"
|
|
29
|
+
| "brightMagenta";
|
|
30
|
+
|
|
31
|
+
/** A color value: named preset, 256-color index (0-255), or hex string (#rrggbb). */
|
|
32
|
+
export type HudColorValue = HudColorName | number | string;
|
|
33
|
+
|
|
34
|
+
export interface HudColorOverrides {
|
|
35
|
+
context: HudColorValue;
|
|
36
|
+
warning: HudColorValue;
|
|
37
|
+
critical: HudColorValue;
|
|
38
|
+
model: HudColorValue;
|
|
39
|
+
project: HudColorValue;
|
|
40
|
+
git: HudColorValue;
|
|
41
|
+
gitBranch: HudColorValue;
|
|
42
|
+
label: HudColorValue;
|
|
43
|
+
custom: HudColorValue;
|
|
44
|
+
barFilled: string;
|
|
45
|
+
barEmpty: string;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export const DEFAULT_ELEMENT_ORDER: HudElement[] = [
|
|
49
|
+
"project",
|
|
50
|
+
"context",
|
|
51
|
+
"promptCache",
|
|
52
|
+
"memory",
|
|
53
|
+
"environment",
|
|
54
|
+
"tools",
|
|
55
|
+
"sessionTime",
|
|
56
|
+
];
|
|
57
|
+
|
|
58
|
+
const KNOWN_ELEMENTS = new Set<HudElement>(DEFAULT_ELEMENT_ORDER);
|
|
59
|
+
|
|
60
|
+
export interface HudConfig {
|
|
61
|
+
language: Language;
|
|
62
|
+
lineLayout: LineLayoutType;
|
|
63
|
+
showSeparators: boolean;
|
|
64
|
+
pathLevels: 1 | 2 | 3;
|
|
65
|
+
elementOrder: HudElement[];
|
|
66
|
+
/** Shell command whose output is shown as an Extra command Line. "" = off. */
|
|
67
|
+
extraCommand: string;
|
|
68
|
+
gitStatus: {
|
|
69
|
+
enabled: boolean;
|
|
70
|
+
showDirty: boolean;
|
|
71
|
+
showAheadBehind: boolean;
|
|
72
|
+
showFileStats: boolean;
|
|
73
|
+
branchOverflow: GitBranchOverflowMode;
|
|
74
|
+
pushWarningThreshold: number;
|
|
75
|
+
pushCriticalThreshold: number;
|
|
76
|
+
};
|
|
77
|
+
display: {
|
|
78
|
+
showModel: boolean;
|
|
79
|
+
showProject: boolean;
|
|
80
|
+
showContextBar: boolean;
|
|
81
|
+
contextValue: ContextValueMode;
|
|
82
|
+
showConfigCounts: boolean;
|
|
83
|
+
showCost: boolean;
|
|
84
|
+
showDuration: boolean;
|
|
85
|
+
showSpeed: boolean;
|
|
86
|
+
showTokenBreakdown: boolean;
|
|
87
|
+
showTools: boolean;
|
|
88
|
+
toolNameMaxLength: number;
|
|
89
|
+
toolsMaxVisible: number;
|
|
90
|
+
showSessionName: boolean;
|
|
91
|
+
showVersion: boolean;
|
|
92
|
+
showThinkingLevel: boolean;
|
|
93
|
+
showMemoryUsage: boolean;
|
|
94
|
+
showPromptCache: boolean;
|
|
95
|
+
promptCacheTtlSeconds: number;
|
|
96
|
+
showSessionTokens: boolean;
|
|
97
|
+
showSessionStartDate: boolean;
|
|
98
|
+
showLastResponseAt: boolean;
|
|
99
|
+
showExtensionStatuses: boolean;
|
|
100
|
+
mergeGroups: HudElement[][];
|
|
101
|
+
contextWarningThreshold: number;
|
|
102
|
+
contextCriticalThreshold: number;
|
|
103
|
+
environmentThreshold: number;
|
|
104
|
+
modelFormat: ModelFormatMode;
|
|
105
|
+
modelOverride: string;
|
|
106
|
+
customLine: string;
|
|
107
|
+
customLinePosition: CustomLinePosition;
|
|
108
|
+
timeFormat: TimeFormatMode;
|
|
109
|
+
};
|
|
110
|
+
colors: HudColorOverrides;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export const DEFAULT_CONFIG: HudConfig = {
|
|
114
|
+
language: "en",
|
|
115
|
+
lineLayout: "expanded",
|
|
116
|
+
showSeparators: false,
|
|
117
|
+
pathLevels: 1,
|
|
118
|
+
elementOrder: [...DEFAULT_ELEMENT_ORDER],
|
|
119
|
+
extraCommand: "",
|
|
120
|
+
gitStatus: {
|
|
121
|
+
enabled: true,
|
|
122
|
+
showDirty: true,
|
|
123
|
+
showAheadBehind: false,
|
|
124
|
+
showFileStats: false,
|
|
125
|
+
branchOverflow: "truncate",
|
|
126
|
+
pushWarningThreshold: 0,
|
|
127
|
+
pushCriticalThreshold: 0,
|
|
128
|
+
},
|
|
129
|
+
display: {
|
|
130
|
+
showModel: true,
|
|
131
|
+
showProject: true,
|
|
132
|
+
showContextBar: true,
|
|
133
|
+
contextValue: "percent",
|
|
134
|
+
showConfigCounts: false,
|
|
135
|
+
showCost: false,
|
|
136
|
+
showDuration: false,
|
|
137
|
+
showSpeed: false,
|
|
138
|
+
showTokenBreakdown: true,
|
|
139
|
+
showTools: false,
|
|
140
|
+
toolNameMaxLength: 0,
|
|
141
|
+
toolsMaxVisible: 4,
|
|
142
|
+
showSessionName: false,
|
|
143
|
+
showVersion: false,
|
|
144
|
+
showThinkingLevel: false,
|
|
145
|
+
showMemoryUsage: false,
|
|
146
|
+
showPromptCache: false,
|
|
147
|
+
promptCacheTtlSeconds: 300,
|
|
148
|
+
showSessionTokens: false,
|
|
149
|
+
showSessionStartDate: false,
|
|
150
|
+
showLastResponseAt: false,
|
|
151
|
+
showExtensionStatuses: true,
|
|
152
|
+
mergeGroups: [],
|
|
153
|
+
contextWarningThreshold: 70,
|
|
154
|
+
contextCriticalThreshold: 85,
|
|
155
|
+
environmentThreshold: 0,
|
|
156
|
+
modelFormat: "full",
|
|
157
|
+
modelOverride: "",
|
|
158
|
+
customLine: "",
|
|
159
|
+
customLinePosition: "last",
|
|
160
|
+
timeFormat: "relative",
|
|
161
|
+
},
|
|
162
|
+
colors: {
|
|
163
|
+
context: "green",
|
|
164
|
+
warning: "yellow",
|
|
165
|
+
critical: "red",
|
|
166
|
+
model: "cyan",
|
|
167
|
+
project: "yellow",
|
|
168
|
+
git: "magenta",
|
|
169
|
+
gitBranch: "cyan",
|
|
170
|
+
label: "dim",
|
|
171
|
+
custom: 208,
|
|
172
|
+
barFilled: "█",
|
|
173
|
+
barEmpty: "░",
|
|
174
|
+
},
|
|
175
|
+
};
|
|
176
|
+
|
|
177
|
+
export type Raw = Record<string, unknown>;
|
|
178
|
+
|
|
179
|
+
export function isObject(value: unknown): value is Raw {
|
|
180
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
function bool(value: unknown, fallback: boolean): boolean {
|
|
184
|
+
return typeof value === "boolean" ? value : fallback;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function oneOf<T>(value: unknown, allowed: readonly T[], fallback: T): T {
|
|
188
|
+
return allowed.includes(value as T) ? (value as T) : fallback;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
const COLOR_NAMES: readonly HudColorName[] = ["dim", "red", "green", "yellow", "magenta", "cyan", "brightBlue", "brightMagenta"];
|
|
192
|
+
// Stricter than sanitize(): a bar glyph is rejected, not stripped, if any codepoint is a control, format, variation selector or unassigned.
|
|
193
|
+
const UNSAFE_CODEPOINT = /[\p{Cc}\p{Cf}\p{Variation_Selector}\p{Zl}\p{Zp}\p{Cn}]/u;
|
|
194
|
+
const HEX_COLOR_PATTERN = /^#[0-9a-fA-F]{6}$/;
|
|
195
|
+
|
|
196
|
+
function validateBarChar(value: unknown): value is string {
|
|
197
|
+
if (typeof value !== "string" || value.length === 0) return false;
|
|
198
|
+
|
|
199
|
+
const segmenter = new Intl.Segmenter(undefined, { granularity: "grapheme" });
|
|
200
|
+
if (Array.from(segmenter.segment(value)).length !== 1) return false;
|
|
201
|
+
|
|
202
|
+
for (const ch of value) {
|
|
203
|
+
if (UNSAFE_CODEPOINT.test(ch)) return false;
|
|
204
|
+
}
|
|
205
|
+
return true;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
function validateColorValue(value: unknown): value is HudColorValue {
|
|
209
|
+
if (COLOR_NAMES.includes(value as HudColorName)) return true;
|
|
210
|
+
if (typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= 255) return true;
|
|
211
|
+
return typeof value === "string" && HEX_COLOR_PATTERN.test(value);
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
function validateElementOrder(value: unknown): HudElement[] {
|
|
215
|
+
if (!Array.isArray(value)) return [...DEFAULT_ELEMENT_ORDER];
|
|
216
|
+
const elementOrder = [...new Set(value.filter((item): item is HudElement => KNOWN_ELEMENTS.has(item)))];
|
|
217
|
+
return elementOrder.length > 0 ? elementOrder : [...DEFAULT_ELEMENT_ORDER];
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
// claude-hud falls back to its default group when nothing valid survives; our default is [] so every invalid case is [].
|
|
221
|
+
function validateMergeGroups(value: unknown): HudElement[][] {
|
|
222
|
+
if (!Array.isArray(value)) return [];
|
|
223
|
+
|
|
224
|
+
const usedElements = new Set<HudElement>();
|
|
225
|
+
const mergeGroups: HudElement[][] = [];
|
|
226
|
+
|
|
227
|
+
for (const group of value) {
|
|
228
|
+
if (!Array.isArray(group)) continue;
|
|
229
|
+
const normalizedGroup = [
|
|
230
|
+
...new Set(group.filter((item): item is HudElement => KNOWN_ELEMENTS.has(item) && !usedElements.has(item))),
|
|
231
|
+
];
|
|
232
|
+
if (normalizedGroup.length >= 2) {
|
|
233
|
+
normalizedGroup.forEach((element) => usedElements.add(element));
|
|
234
|
+
mergeGroups.push(normalizedGroup);
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
return mergeGroups;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
function validateThreshold(value: unknown, max = 100): number {
|
|
242
|
+
if (typeof value !== "number") return 0;
|
|
243
|
+
return Math.max(0, Math.min(max, value));
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
function validateContextThreshold(value: unknown, fallback: number): number {
|
|
247
|
+
if (typeof value !== "number" || !Number.isFinite(value)) return fallback;
|
|
248
|
+
return Math.max(0, Math.min(100, value));
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
function validateCountThreshold(value: unknown): number {
|
|
252
|
+
if (typeof value !== "number" || !Number.isFinite(value)) return 0;
|
|
253
|
+
return Math.max(0, Math.floor(value));
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
function validateDurationSeconds(value: unknown, fallback: number): number {
|
|
257
|
+
if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) return fallback;
|
|
258
|
+
return Math.floor(value);
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
function validateNonNegativeInteger(value: unknown, fallback: number): number {
|
|
262
|
+
if (typeof value !== "number" || !Number.isInteger(value) || value < 0) return fallback;
|
|
263
|
+
return value;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
function truncatedString(value: unknown, fallback: string): string {
|
|
267
|
+
return typeof value === "string" ? value.slice(0, 80) : fallback;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/** Validates a parsed user config field by field. Invalid values fall back to the field's default; unknown fields are dropped. */
|
|
271
|
+
export function mergeConfig(userConfig: unknown): HudConfig {
|
|
272
|
+
const user = isObject(userConfig) ? userConfig : {};
|
|
273
|
+
const git = isObject(user.gitStatus) ? user.gitStatus : {};
|
|
274
|
+
const display = isObject(user.display) ? user.display : {};
|
|
275
|
+
const colors = isObject(user.colors) ? user.colors : {};
|
|
276
|
+
const D = DEFAULT_CONFIG;
|
|
277
|
+
|
|
278
|
+
const color = (key: Exclude<keyof HudColorOverrides, "barFilled" | "barEmpty">) =>
|
|
279
|
+
validateColorValue(colors[key]) ? colors[key] : D.colors[key];
|
|
280
|
+
const barChar = (key: "barFilled" | "barEmpty") => (validateBarChar(colors[key]) ? colors[key] : D.colors[key]);
|
|
281
|
+
const displayBool = (key: { [K in keyof HudConfig["display"]]: HudConfig["display"][K] extends boolean ? K : never }[keyof HudConfig["display"]]) =>
|
|
282
|
+
bool(display[key], D.display[key]);
|
|
283
|
+
|
|
284
|
+
return {
|
|
285
|
+
language: user.language === "zh" ? "zh-Hans" : oneOf(user.language, ["en", "zh-Hans"] as const, D.language),
|
|
286
|
+
lineLayout: oneOf(user.lineLayout, ["compact", "expanded"] as const, D.lineLayout),
|
|
287
|
+
showSeparators: bool(user.showSeparators, D.showSeparators),
|
|
288
|
+
pathLevels: oneOf(user.pathLevels, [1, 2, 3] as const, D.pathLevels),
|
|
289
|
+
elementOrder: validateElementOrder(user.elementOrder),
|
|
290
|
+
extraCommand: typeof user.extraCommand === "string" ? user.extraCommand : D.extraCommand,
|
|
291
|
+
gitStatus: {
|
|
292
|
+
enabled: bool(git.enabled, D.gitStatus.enabled),
|
|
293
|
+
showDirty: bool(git.showDirty, D.gitStatus.showDirty),
|
|
294
|
+
showAheadBehind: bool(git.showAheadBehind, D.gitStatus.showAheadBehind),
|
|
295
|
+
showFileStats: bool(git.showFileStats, D.gitStatus.showFileStats),
|
|
296
|
+
branchOverflow: oneOf(git.branchOverflow, ["truncate", "wrap"] as const, D.gitStatus.branchOverflow),
|
|
297
|
+
pushWarningThreshold: validateCountThreshold(git.pushWarningThreshold),
|
|
298
|
+
pushCriticalThreshold: validateCountThreshold(git.pushCriticalThreshold),
|
|
299
|
+
},
|
|
300
|
+
display: {
|
|
301
|
+
showModel: displayBool("showModel"),
|
|
302
|
+
showProject: displayBool("showProject"),
|
|
303
|
+
showContextBar: displayBool("showContextBar"),
|
|
304
|
+
contextValue: oneOf(display.contextValue, ["percent", "tokens", "remaining", "both"] as const, D.display.contextValue),
|
|
305
|
+
showConfigCounts: displayBool("showConfigCounts"),
|
|
306
|
+
showCost: displayBool("showCost"),
|
|
307
|
+
showDuration: displayBool("showDuration"),
|
|
308
|
+
showSpeed: displayBool("showSpeed"),
|
|
309
|
+
showTokenBreakdown: displayBool("showTokenBreakdown"),
|
|
310
|
+
showTools: displayBool("showTools"),
|
|
311
|
+
toolNameMaxLength: validateNonNegativeInteger(display.toolNameMaxLength, D.display.toolNameMaxLength),
|
|
312
|
+
toolsMaxVisible: validateNonNegativeInteger(display.toolsMaxVisible, D.display.toolsMaxVisible),
|
|
313
|
+
showSessionName: displayBool("showSessionName"),
|
|
314
|
+
showVersion: displayBool("showVersion"),
|
|
315
|
+
showThinkingLevel: displayBool("showThinkingLevel"),
|
|
316
|
+
showMemoryUsage: displayBool("showMemoryUsage"),
|
|
317
|
+
showPromptCache: displayBool("showPromptCache"),
|
|
318
|
+
promptCacheTtlSeconds: validateDurationSeconds(display.promptCacheTtlSeconds, D.display.promptCacheTtlSeconds),
|
|
319
|
+
showSessionTokens: displayBool("showSessionTokens"),
|
|
320
|
+
showSessionStartDate: displayBool("showSessionStartDate"),
|
|
321
|
+
showLastResponseAt: displayBool("showLastResponseAt"),
|
|
322
|
+
showExtensionStatuses: displayBool("showExtensionStatuses"),
|
|
323
|
+
mergeGroups: validateMergeGroups(display.mergeGroups),
|
|
324
|
+
contextWarningThreshold: validateContextThreshold(display.contextWarningThreshold, D.display.contextWarningThreshold),
|
|
325
|
+
contextCriticalThreshold: validateContextThreshold(display.contextCriticalThreshold, D.display.contextCriticalThreshold),
|
|
326
|
+
environmentThreshold: validateThreshold(display.environmentThreshold, 100),
|
|
327
|
+
modelFormat: oneOf(display.modelFormat, ["full", "compact", "short"] as const, D.display.modelFormat),
|
|
328
|
+
modelOverride: truncatedString(display.modelOverride, D.display.modelOverride),
|
|
329
|
+
customLine: truncatedString(display.customLine, D.display.customLine),
|
|
330
|
+
customLinePosition: oneOf(display.customLinePosition, ["first", "last"] as const, D.display.customLinePosition),
|
|
331
|
+
timeFormat: oneOf(
|
|
332
|
+
display.timeFormat,
|
|
333
|
+
["relative", "absolute", "both", "elapsed", "elapsedAndAbsolute"] as const,
|
|
334
|
+
D.display.timeFormat,
|
|
335
|
+
),
|
|
336
|
+
},
|
|
337
|
+
colors: {
|
|
338
|
+
context: color("context"),
|
|
339
|
+
warning: color("warning"),
|
|
340
|
+
critical: color("critical"),
|
|
341
|
+
model: color("model"),
|
|
342
|
+
project: color("project"),
|
|
343
|
+
git: color("git"),
|
|
344
|
+
gitBranch: color("gitBranch"),
|
|
345
|
+
label: color("label"),
|
|
346
|
+
custom: color("custom"),
|
|
347
|
+
barFilled: barChar("barFilled"),
|
|
348
|
+
barEmpty: barChar("barEmpty"),
|
|
349
|
+
},
|
|
350
|
+
};
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
/** Objects merge recursively; arrays and scalars from `override` replace. */
|
|
354
|
+
export function deepMerge(base: Raw, override: Raw): Raw {
|
|
355
|
+
const merged: Raw = { ...base };
|
|
356
|
+
for (const [key, value] of Object.entries(override)) {
|
|
357
|
+
const current = merged[key];
|
|
358
|
+
merged[key] = isObject(value) && isObject(current) ? deepMerge(current, value) : value;
|
|
359
|
+
}
|
|
360
|
+
return merged;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
/** Missing, unreadable, unparseable or non-object files count as empty so the HUD still renders. */
|
|
364
|
+
function readJsonObject(file: string): Raw {
|
|
365
|
+
try {
|
|
366
|
+
const parsed: unknown = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
367
|
+
return isObject(parsed) ? parsed : {};
|
|
368
|
+
} catch {
|
|
369
|
+
return {};
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
/** Reads `<agentDir>/pi-hud-plus.json`, the only config file (see docs/adr/0001-global-config-only.md). */
|
|
374
|
+
export function loadConfig(agentDir: string): HudConfig {
|
|
375
|
+
return mergeConfig(readJsonObject(path.join(agentDir, "pi-hud-plus.json")));
|
|
376
|
+
}
|
package/src/extra-cmd.ts
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
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. No debug logging.
|
|
3
|
+
import type { Exec } from "./git.ts";
|
|
4
|
+
import { sanitize as stripControls } from "./sanitize.ts";
|
|
5
|
+
|
|
6
|
+
const MAX_BUFFER = 10 * 1024; // 10KB - plenty for a label
|
|
7
|
+
const MAX_LABEL_LENGTH = 50;
|
|
8
|
+
const TIMEOUT_MS = 3000;
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Sanitize output to prevent terminal escape injection.
|
|
12
|
+
* Strips whole ANSI/OSC escape sequences (so their parameters don't show), then control and bidi characters.
|
|
13
|
+
*/
|
|
14
|
+
export function sanitize(input: string): string {
|
|
15
|
+
return stripControls(
|
|
16
|
+
input
|
|
17
|
+
.replace(/\x1B\[[0-?]*[ -/]*[@-~]/g, "") // CSI sequences
|
|
18
|
+
.replace(/\x1B\][^\x07\x1B]*(?:\x07|\x1B\\)/g, "") // OSC sequences
|
|
19
|
+
.replace(/\x1B[@-Z\\-_]/g, ""), // 7-bit C1 / ESC Fe
|
|
20
|
+
);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Run the Extra command and parse its JSON output, expecting { label: string }.
|
|
25
|
+
* Returns null on any error (timeout, non-zero exit, parse failure, missing label).
|
|
26
|
+
*
|
|
27
|
+
* SECURITY NOTE: cmd comes only from the user's global config; project config files aren't read
|
|
28
|
+
* (see loadConfig), so opening a repo can't run commands.
|
|
29
|
+
*/
|
|
30
|
+
export async function runExtraCmd(exec: Exec, cmd: string, timeout: number = TIMEOUT_MS): Promise<string | null> {
|
|
31
|
+
try {
|
|
32
|
+
const { stdout, code, killed } = await exec("sh", ["-c", cmd], { timeout, maxBuffer: MAX_BUFFER });
|
|
33
|
+
if (code !== 0 || killed) return null;
|
|
34
|
+
const data: unknown = JSON.parse(stdout.trim());
|
|
35
|
+
if (typeof data === "object" && data !== null && "label" in data && typeof data.label === "string") {
|
|
36
|
+
let label = sanitize(data.label);
|
|
37
|
+
if (label.length > MAX_LABEL_LENGTH) {
|
|
38
|
+
label = label.slice(0, MAX_LABEL_LENGTH - 1) + "…";
|
|
39
|
+
}
|
|
40
|
+
return label;
|
|
41
|
+
}
|
|
42
|
+
return null;
|
|
43
|
+
} catch {
|
|
44
|
+
return null;
|
|
45
|
+
}
|
|
46
|
+
}
|
package/src/git.ts
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
// Ported from claude-hud src/git.ts. Changes for pi: commands go through pi.exec (which resolves with an
|
|
2
|
+
// exit code instead of rejecting), every command passes --no-optional-locks, diff and rev-list are gated
|
|
3
|
+
// by config, and the branch (rev-parse) and branchUrl (remote get-url) come from elsewhere / are dropped.
|
|
4
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
5
|
+
|
|
6
|
+
export type Exec = ExtensionAPI["exec"];
|
|
7
|
+
|
|
8
|
+
export interface LineDiff {
|
|
9
|
+
added: number;
|
|
10
|
+
deleted: number;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export interface TrackedFile {
|
|
14
|
+
basename: string;
|
|
15
|
+
fullPath: string;
|
|
16
|
+
type: 'modified' | 'added' | 'deleted';
|
|
17
|
+
lineDiff?: LineDiff;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface FileStats {
|
|
21
|
+
modified: number;
|
|
22
|
+
added: number;
|
|
23
|
+
deleted: number;
|
|
24
|
+
untracked: number;
|
|
25
|
+
trackedFiles: TrackedFile[];
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface GitStatus {
|
|
29
|
+
branch: string;
|
|
30
|
+
isDirty: boolean;
|
|
31
|
+
ahead: number;
|
|
32
|
+
behind: number;
|
|
33
|
+
fileStats?: FileStats;
|
|
34
|
+
lineDiff?: LineDiff;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface GitStatusOptions {
|
|
38
|
+
showAheadBehind: boolean;
|
|
39
|
+
showFileStats: boolean;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Runs `git --no-optional-locks <args>`, rejecting like execFile on a non-zero exit or timeout. */
|
|
43
|
+
async function git(exec: Exec, cwd: string, args: string[], timeout: number): Promise<string> {
|
|
44
|
+
const result = await exec('git', ['--no-optional-locks', ...args], { cwd, timeout });
|
|
45
|
+
if (result.code !== 0 || result.killed) throw new Error(`git ${args.join(' ')} exited ${result.code}`);
|
|
46
|
+
return result.stdout;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export async function getGitStatus(exec: Exec, cwd: string, options: GitStatusOptions): Promise<Omit<GitStatus, 'branch'>> {
|
|
50
|
+
// Check for dirty state and parse file stats
|
|
51
|
+
let isDirty = false;
|
|
52
|
+
let fileStats: FileStats | undefined;
|
|
53
|
+
let lineDiff: LineDiff | undefined;
|
|
54
|
+
try {
|
|
55
|
+
const statusOut = await git(exec, cwd, ['-c', 'core.quotePath=false', 'status', '--porcelain'], 1000);
|
|
56
|
+
const trimmed = statusOut.trim();
|
|
57
|
+
isDirty = trimmed.length > 0;
|
|
58
|
+
if (isDirty) {
|
|
59
|
+
fileStats = parseFileStats(trimmed);
|
|
60
|
+
}
|
|
61
|
+
} catch {
|
|
62
|
+
// Ignore errors, assume clean
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// Get per-file and total line diffs. diff can refresh the index, so it only runs when shown.
|
|
66
|
+
if (isDirty && options.showFileStats) {
|
|
67
|
+
try {
|
|
68
|
+
const numstatOut = await git(exec, cwd, ['-c', 'core.quotePath=false', 'diff', '--numstat', 'HEAD'], 2000);
|
|
69
|
+
const trackedPaths = new Set(fileStats?.trackedFiles.map((file) => file.fullPath) ?? []);
|
|
70
|
+
const { totalDiff, perFileDiff } = parseNumstat(numstatOut, trackedPaths);
|
|
71
|
+
lineDiff = totalDiff;
|
|
72
|
+
if (fileStats) {
|
|
73
|
+
applyLineDiffsToFiles(fileStats.trackedFiles, perFileDiff);
|
|
74
|
+
}
|
|
75
|
+
} catch {
|
|
76
|
+
// Ignore errors
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// Get ahead/behind counts
|
|
81
|
+
let ahead = 0;
|
|
82
|
+
let behind = 0;
|
|
83
|
+
if (options.showAheadBehind) {
|
|
84
|
+
try {
|
|
85
|
+
const revOut = await git(exec, cwd, ['rev-list', '--left-right', '--count', '@{upstream}...HEAD'], 1000);
|
|
86
|
+
const parts = revOut.trim().split(/\s+/);
|
|
87
|
+
if (parts.length === 2) {
|
|
88
|
+
behind = parseInt(parts[0]!, 10) || 0;
|
|
89
|
+
ahead = parseInt(parts[1]!, 10) || 0;
|
|
90
|
+
}
|
|
91
|
+
} catch {
|
|
92
|
+
// No upstream or error, keep 0/0
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
return { isDirty, ahead, behind, fileStats, lineDiff };
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Parse git status --porcelain output and count file stats (Starship-compatible format)
|
|
101
|
+
* Status codes: M=modified, A=added, D=deleted, ??=untracked
|
|
102
|
+
*/
|
|
103
|
+
function parseFileStats(porcelainOutput: string): FileStats {
|
|
104
|
+
const stats: FileStats = { modified: 0, added: 0, deleted: 0, untracked: 0, trackedFiles: [] };
|
|
105
|
+
const lines = porcelainOutput.split('\n').filter(Boolean);
|
|
106
|
+
|
|
107
|
+
for (const line of lines) {
|
|
108
|
+
if (line.length < 2) continue;
|
|
109
|
+
|
|
110
|
+
const index = line[0]; // staged status
|
|
111
|
+
const worktree = line[1]; // unstaged status
|
|
112
|
+
|
|
113
|
+
if (line.startsWith('??')) {
|
|
114
|
+
stats.untracked++;
|
|
115
|
+
} else if (index === 'A') {
|
|
116
|
+
stats.added++;
|
|
117
|
+
const fullPath = parsePorcelainPath(line.slice(2).trimStart());
|
|
118
|
+
stats.trackedFiles.push({ basename: fullPath.split('/').pop() ?? fullPath, fullPath, type: 'added' });
|
|
119
|
+
} else if (index === 'D' || worktree === 'D') {
|
|
120
|
+
stats.deleted++;
|
|
121
|
+
const fullPath = parsePorcelainPath(line.slice(2).trimStart());
|
|
122
|
+
stats.trackedFiles.push({ basename: fullPath.split('/').pop() ?? fullPath, fullPath, type: 'deleted' });
|
|
123
|
+
} else if (index === 'M' || worktree === 'M' || index === 'R' || index === 'C') {
|
|
124
|
+
// M=modified, R=renamed (counts as modified), C=copied (counts as modified)
|
|
125
|
+
stats.modified++;
|
|
126
|
+
// For renames, git porcelain shows "old -> new"; take the destination path
|
|
127
|
+
const fullPath = parsePorcelainPath(line.slice(2).trimStart().split(' -> ').pop() ?? line.slice(2).trimStart());
|
|
128
|
+
stats.trackedFiles.push({ basename: fullPath.split('/').pop() ?? fullPath, fullPath, type: 'modified' });
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
return stats;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function parsePorcelainPath(pathField: string): string {
|
|
136
|
+
if (pathField.startsWith('"') && pathField.endsWith('"')) {
|
|
137
|
+
try {
|
|
138
|
+
return JSON.parse(pathField);
|
|
139
|
+
} catch {
|
|
140
|
+
return pathField.slice(1, -1);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
return pathField;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* Extract the destination path from a numstat path field.
|
|
149
|
+
*
|
|
150
|
+
* For renames, `git diff --numstat` emits the path as `old => new`
|
|
151
|
+
* (sometimes with a shared directory prefix like `pkg/{old.ts => new.ts}`).
|
|
152
|
+
* `git status --porcelain` reports the renamed file under its destination
|
|
153
|
+
* only, so we key `perFileDiff` by the destination to make lookups match.
|
|
154
|
+
*/
|
|
155
|
+
function extractNumstatDestination(filePath: string): string {
|
|
156
|
+
const braceMatch = filePath.match(/^(.*)\{(.*) => (.*)\}(.*)$/);
|
|
157
|
+
if (braceMatch) {
|
|
158
|
+
const [, prefix, , dest, suffix] = braceMatch;
|
|
159
|
+
return `${prefix}${dest}${suffix}`.replace(/\/{2,}/g, '/');
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
const arrowIndex = filePath.indexOf(' => ');
|
|
163
|
+
if (arrowIndex !== -1) {
|
|
164
|
+
return filePath.slice(arrowIndex + 4);
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
return filePath;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function resolveNumstatPath(filePath: string, trackedPaths: Set<string>): string {
|
|
171
|
+
if (trackedPaths.has(filePath)) {
|
|
172
|
+
return filePath;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
const destinationPath = extractNumstatDestination(filePath);
|
|
176
|
+
if (destinationPath !== filePath && trackedPaths.has(destinationPath)) {
|
|
177
|
+
return destinationPath;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
return filePath;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* Parse `git diff --numstat HEAD` output.
|
|
185
|
+
* Returns total line diff and a map of fullPath -> LineDiff.
|
|
186
|
+
*/
|
|
187
|
+
function parseNumstat(numstatOutput: string, trackedPaths: Set<string>): { totalDiff: LineDiff; perFileDiff: Map<string, LineDiff> } {
|
|
188
|
+
const totalDiff: LineDiff = { added: 0, deleted: 0 };
|
|
189
|
+
const perFileDiff = new Map<string, LineDiff>();
|
|
190
|
+
|
|
191
|
+
for (const line of numstatOutput.trim().split('\n').filter(Boolean)) {
|
|
192
|
+
const parts = line.split('\t');
|
|
193
|
+
if (parts.length < 3) continue;
|
|
194
|
+
const added = parseInt(parts[0]!, 10);
|
|
195
|
+
const deleted = parseInt(parts[1]!, 10);
|
|
196
|
+
const filePath = resolveNumstatPath(parts[2]!, trackedPaths);
|
|
197
|
+
if (Number.isNaN(added) || Number.isNaN(deleted)) continue; // binary file
|
|
198
|
+
totalDiff.added += added;
|
|
199
|
+
totalDiff.deleted += deleted;
|
|
200
|
+
perFileDiff.set(filePath, { added, deleted });
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
return { totalDiff, perFileDiff };
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
function applyLineDiffsToFiles(files: TrackedFile[], perFileDiff: Map<string, LineDiff>): void {
|
|
207
|
+
for (const file of files) {
|
|
208
|
+
const diff = perFileDiff.get(file.fullPath);
|
|
209
|
+
if (diff) {
|
|
210
|
+
file.lineDiff = diff;
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
}
|
package/src/i18n/en.ts
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type { Messages } from "./types.ts";
|
|
2
|
+
|
|
3
|
+
export const en: Messages = {
|
|
4
|
+
// Labels
|
|
5
|
+
"label.context": "Context",
|
|
6
|
+
"label.approxRam": "Approx RAM",
|
|
7
|
+
"label.promptCache": "Cache",
|
|
8
|
+
"label.estimatedCost": "Est.",
|
|
9
|
+
"label.cost": "Cost",
|
|
10
|
+
"label.tokens": "Tokens",
|
|
11
|
+
"label.sessionStarted": "Started",
|
|
12
|
+
"label.lastReply": "Last reply",
|
|
13
|
+
"label.skills": "skills",
|
|
14
|
+
"label.prompts": "prompts",
|
|
15
|
+
|
|
16
|
+
// Status
|
|
17
|
+
"status.expired": "expired",
|
|
18
|
+
|
|
19
|
+
// Format
|
|
20
|
+
"format.at": "at",
|
|
21
|
+
"format.in": "in",
|
|
22
|
+
"format.cache": "cache",
|
|
23
|
+
"format.out": "out",
|
|
24
|
+
"format.tok": "tok",
|
|
25
|
+
"format.tokPerSec": "tok/s",
|
|
26
|
+
"format.justNow": "just now",
|
|
27
|
+
"format.ago": "ago",
|
|
28
|
+
};
|