pi-hud-plus 0.1.0 → 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 CHANGED
@@ -1,5 +1,15 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.2.0] - 2026-11-17
4
+
5
+ ### New Features
6
+
7
+ - **`/pi-hud:setup` and `/pi-hud:configure`**: guided config in a settings list (layout, language, git style, Elements, Custom line, Presets). Changes are confirmed, written to `~/.pi/agent/pi-hud-plus.json` and reloaded.
8
+
9
+ ### Breaking Changes
10
+
11
+ - **Global config only**: `.pi/pi-hud-plus.json` in a project is no longer read. Move its fields into `~/.pi/agent/pi-hud-plus.json`.
12
+
3
13
  ## [0.1.0] - 2026-11-14
4
14
 
5
15
  ### New Features
package/README.md CHANGED
@@ -18,6 +18,15 @@ pi -e npm:pi-hud-plus
18
18
 
19
19
  The HUD runs only in pi's interactive TUI. Print, JSON and RPC modes are left alone.
20
20
 
21
+ ## Commands
22
+
23
+ - `/pi-hud:setup` asks for a layout, a Preset (Full, Essential or Minimal) and a language, then opens a settings list pre-filled from the Preset.
24
+ - `/pi-hud:configure` opens the same list on your current config. With no config file yet, it runs setup's questions first.
25
+
26
+ In the list, Enter or Space changes a row. The rows are layout, language, git style (`off`, `branch`, `branch+dirty`, `full`, `file stats`), one on/off row per Element, the Custom line, and Reset to preset. Press Esc when you're done: you'll see the changes and confirm before anything is saved. pi-hud-plus then writes `~/.pi/agent/pi-hud-plus.json` and reloads.
27
+
28
+ Only the rows you changed are written. Every other field in the file is kept, including colors, thresholds and `extraCommand`. If the file isn't valid JSON, the commands refuse to touch it.
29
+
21
30
  ## Lines and Elements
22
31
 
23
32
  The default `lineLayout` is `"expanded"`: one Line per Element, in `elementOrder`. Lines with nothing to show are left out. Every Line is cut to the terminal width with `…`.
@@ -45,14 +54,9 @@ With `"lineLayout": "compact"`, everything goes on one session Line (model badge
45
54
 
46
55
  ## Config
47
56
 
48
- pi-hud-plus reads two JSON files:
57
+ pi-hud-plus reads one JSON file, `~/.pi/agent/pi-hud-plus.json`, for every project. There's no per-project file. The file is optional. A file that is missing or doesn't parse counts as empty, so the HUD still renders. Each field is validated on its own: an invalid value falls back to that field's default, and unknown fields are ignored.
49
58
 
50
- - global: `~/.pi/agent/pi-hud-plus.json`
51
- - project: `<cwd>/.pi/pi-hud-plus.json`
52
-
53
- The project file is deep-merged over the global one. Objects merge key by key, while arrays and plain values replace. Both files are optional. A file that is missing or doesn't parse counts as empty, so the HUD still renders. Each field is validated on its own: an invalid value falls back to that field's default, and unknown fields are ignored.
54
-
55
- The files are read when a session starts. After editing one, run `/reload`.
59
+ The file is read when a session starts. After editing it, run `/reload`.
56
60
 
57
61
  ### Field reference
58
62
 
@@ -65,7 +69,7 @@ Top level:
65
69
  | `showSeparators` | `false` | boolean |
66
70
  | `pathLevels` | `1` | `1`, `2`, `3`: how many trailing directories of the cwd to show |
67
71
  | `elementOrder` | `["project", "context", "promptCache", "memory", "environment", "tools", "sessionTime"]` | Elements in Line order. Leaving an Element out hides its Line. Unknown ids and duplicates are dropped |
68
- | `extraCommand` | `""` (off) | shell command, see [Extra command](#extra-command). Global file only |
72
+ | `extraCommand` | `""` (off) | shell command, see [Extra command](#extra-command) |
69
73
 
70
74
  `gitStatus`:
71
75
 
@@ -171,8 +175,6 @@ Then run `/reload`.
171
175
 
172
176
  It runs when a session starts, after each agent run, and every 30 seconds. Each run has a 3-second timeout. Control and escape characters are stripped from the label, and it is cut to 50 characters. If the command fails, times out or prints anything else, no label is shown.
173
177
 
174
- `extraCommand` is **ignored in the project file**. It runs a shell command, and a project file comes with whatever repository you open. Reading it from there would let a cloned repo run commands on your machine just by being opened. Set it in `~/.pi/agent/pi-hud-plus.json`.
175
-
176
178
  ## Coexisting with other footer extensions
177
179
 
178
180
  pi has one footer, and the last extension to set it wins. Other extensions' footer statuses aren't lost: they show on the HUD's Extension statuses Line.
@@ -195,8 +197,8 @@ To see the HUD, disable the other footer extension with `pi config`, then start
195
197
  - **Renamed fields, no aliases**: `display.showClaudeCodeVersion` is `display.showVersion`, and `display.showEffortLevel` is `display.showThinkingLevel`.
196
198
  - **Other dropped fields**: `maxWidth` and `forceMaxWidth` (pi gives the HUD its width), `display.showAddedDirs`, `addedDirsLayout`, `showAgents`, `showTodos`, `showOutputStyle` and `autocompactBuffer`.
197
199
  - **Changed defaults**: `mergeGroups` defaults to `[]`, and `elementOrder` has no `usage`, `agents`, `todos` or `addedDirs`.
198
- - **New fields**: `extraCommand` (claude-hud's `--extra-cmd`, now config, and never read from the project file) and `display.showExtensionStatuses`.
199
- - **No setup command**: you configure the HUD by editing the JSON files. There's no `/claude-hud:setup`-style command, and no config file watching.
200
+ - **New fields**: `extraCommand` (claude-hud's `--extra-cmd`, now config) and `display.showExtensionStatuses`.
201
+ - **Commands**: `/pi-hud:setup` and `/pi-hud:configure` replace `/claude-hud:setup` and `/claude-hud:configure`. There's no statusline to install, so setup only writes config, and both use one settings list instead of a series of questions. There's no config file watching: after editing the file by hand, run `/reload`.
200
202
  - **No git files Line**: with `showFileStats` on, claude-hud adds a Line listing the changed files; pi-hud-plus shows only the counts in the git Element.
201
203
  - **No branch link**: claude-hud links the branch name to its remote (`branchUrl`) with a terminal hyperlink; pi-hud-plus shows plain text.
202
204
  - **`max` thinking level**: pi's `max` level, which claude-hud has no equivalent for, shows as `◕` like `xhigh`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-hud-plus",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "A claude-hud-style HUD for pi's footer",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -0,0 +1,213 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import { getAgentDir, getSelectListTheme, getSettingsListTheme, type ExtensionAPI, type ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
4
+ import { Input, SelectList, SettingsList, type Component, type SettingItem } from "@earendil-works/pi-tui";
5
+ import { sanitize } from "./sanitize.ts";
6
+ import { DEFAULT_CONFIG, deepMerge, isObject, mergeConfig, type HudConfig, type Raw } from "./config.ts";
7
+
8
+ /** The guided settings, keyed by settings-list row id; every value is the row's display string. */
9
+ type Values = Record<string, string>;
10
+
11
+ const TOGGLES: [key: keyof HudConfig["display"], label: string][] = [
12
+ ["showTools", "Tools activity"],
13
+ ["showProject", "Project"],
14
+ ["showConfigCounts", "Environment line"],
15
+ ["showTokenBreakdown", "Token breakdown"],
16
+ ["showSpeed", "Output speed"],
17
+ ["showDuration", "Session duration"],
18
+ ["showSessionName", "Session name"],
19
+ ["showSessionTokens", "Session tokens"],
20
+ ["showCost", "Cost"],
21
+ ["showThinkingLevel", "Thinking level"],
22
+ ["showVersion", "Version"],
23
+ ["showMemoryUsage", "Memory"],
24
+ ["showPromptCache", "Prompt cache"],
25
+ ["showExtensionStatuses", "Extension statuses"],
26
+ ["showSessionStartDate", "Session start date"],
27
+ ["showLastResponseAt", "Last response time"],
28
+ ];
29
+
30
+ const LAYOUTS = ["expanded", "compact", "compact+separators"];
31
+ const LANGUAGES = ["en", "zh-Hans"];
32
+ // claude-hud's Git Style Mapping, plus off.
33
+ const GIT_STYLES: Record<string, Partial<HudConfig["gitStatus"]>> = {
34
+ off: { enabled: false },
35
+ branch: { enabled: true, showDirty: false, showAheadBehind: false, showFileStats: false },
36
+ "branch+dirty": { enabled: true, showDirty: true, showAheadBehind: false, showFileStats: false },
37
+ full: { enabled: true, showDirty: true, showAheadBehind: true, showFileStats: false },
38
+ "file stats": { enabled: true, showDirty: true, showAheadBehind: false, showFileStats: true },
39
+ };
40
+ const PRESET_NAMES = ["Full", "Essential", "Minimal"];
41
+
42
+ /** The settings-list rows in display order; rows with `values` cycle through them. */
43
+ const ROWS: { id: string; label: string; values?: string[] }[] = [
44
+ { id: "layout", label: "Layout", values: LAYOUTS },
45
+ { id: "language", label: "Language", values: LANGUAGES },
46
+ { id: "git", label: "Git", values: Object.keys(GIT_STYLES) },
47
+ ...TOGGLES.map(([id, label]) => ({ id, label, values: ["on", "off"] })),
48
+ { id: "customLine", label: "Custom line" },
49
+ ];
50
+ const RESET_ROW = "Reset to preset";
51
+
52
+ function gitStyle(git: HudConfig["gitStatus"]): string {
53
+ if (!git.enabled) return "off";
54
+ if (git.showFileStats) return "file stats";
55
+ if (git.showAheadBehind) return "full";
56
+ return git.showDirty ? "branch+dirty" : "branch";
57
+ }
58
+
59
+ function valuesFrom(config: HudConfig): Values {
60
+ return {
61
+ layout: config.lineLayout === "compact" ? (config.showSeparators ? "compact+separators" : "compact") : "expanded",
62
+ language: config.language,
63
+ git: gitStyle(config.gitStatus),
64
+ ...Object.fromEntries(TOGGLES.map(([key]) => [key, config.display[key] ? "on" : "off"])),
65
+ customLine: config.display.customLine,
66
+ };
67
+ }
68
+
69
+ /** A Preset's rows: the Elements and git style, never layout, language or the Custom line. */
70
+ function preset(name: string): Values {
71
+ const minimal = valuesFrom(DEFAULT_CONFIG);
72
+ delete minimal.layout;
73
+ delete minimal.language;
74
+ delete minimal.customLine;
75
+ if (name === "Full") return { ...minimal, ...Object.fromEntries(TOGGLES.map(([key]) => [key, "on"])) };
76
+ if (name === "Essential") return { ...minimal, showTools: "on", showDuration: "on", showExtensionStatuses: "on" };
77
+ return minimal;
78
+ }
79
+
80
+ /** Only rows that changed are written, so a value the guided rows can't express (e.g. separators in expanded) survives. */
81
+ function toPatch(before: Values, after: Values): Raw {
82
+ const display: Raw = {};
83
+ const patch: Raw = { display };
84
+ for (const { id } of ROWS) {
85
+ const value = after[id]!;
86
+ if (value === before[id]) continue;
87
+ if (id === "layout") Object.assign(patch, { lineLayout: value === "expanded" ? "expanded" : "compact", showSeparators: value === "compact+separators" });
88
+ else if (id === "language") patch.language = value;
89
+ else if (id === "git") patch.gitStatus = GIT_STYLES[value];
90
+ else if (id === "customLine") display.customLine = value;
91
+ else display[id] = value === "on";
92
+ }
93
+ if (!Object.keys(display).length) delete patch.display;
94
+ return patch;
95
+ }
96
+
97
+ function changes(before: Values, after: Values): string[] {
98
+ const shown = (value: string) => value || "(none)";
99
+ return ROWS.filter(({ id }) => before[id] !== after[id]).map(({ id, label }) => `${label}: ${shown(before[id]!)} → ${shown(after[id]!)}`);
100
+ }
101
+
102
+ /** A one-line text prompt; Enter closes with the sanitized text, Esc closes without a value. */
103
+ function textInput(title: string, close: (value?: string) => void): Component {
104
+ const input = new Input();
105
+ input.onSubmit = (value) => close(sanitize(value).trim().slice(0, 80));
106
+ input.onEscape = () => close();
107
+ return {
108
+ render: (width) => [title, ...input.render(width)],
109
+ invalidate: () => input.invalidate(),
110
+ handleInput: (data) => input.handleInput(data),
111
+ };
112
+ }
113
+
114
+ function editValues(ctx: ExtensionCommandContext, start: Values): Promise<Values | undefined> {
115
+ return ctx.ui.custom<Values | undefined>((tui, theme, _kb, done) => {
116
+ const values = { ...start };
117
+ const items: SettingItem[] = ROWS.map((row) => ({ ...row, currentValue: values[row.id]! }));
118
+ items.find((item) => item.id === "customLine")!.submenu = (_current, close) => textInput("Custom line (empty removes it, Esc keeps it):", close);
119
+ items.push({
120
+ id: RESET_ROW,
121
+ label: RESET_ROW,
122
+ currentValue: "",
123
+ description: "Set every Element row and Git to a Preset's values; layout, language and the Custom line stay.",
124
+ submenu: (_current, close) => {
125
+ const presets = new SelectList(PRESET_NAMES.map((name) => ({ value: name, label: name })), PRESET_NAMES.length, getSelectListTheme());
126
+ presets.onSelect = ({ value }) => {
127
+ for (const [id, presetValue] of Object.entries(preset(value))) {
128
+ values[id] = presetValue;
129
+ list.updateValue(id, presetValue);
130
+ }
131
+ close();
132
+ };
133
+ presets.onCancel = () => close();
134
+ return presets;
135
+ },
136
+ });
137
+ const list = new SettingsList(
138
+ items,
139
+ Math.min(items.length, 15),
140
+ getSettingsListTheme(),
141
+ (id, value) => (values[id] = value),
142
+ () => done(values),
143
+ );
144
+ return {
145
+ // The list's own hint says "Esc to cancel"; here Esc ends editing and the save is confirmed next.
146
+ render: (width: number) => [theme.fg("accent", theme.bold("pi-hud-plus · Esc when done, then confirm to save")), "", ...list.render(width)],
147
+ invalidate: () => list.invalidate(),
148
+ handleInput(data: string) {
149
+ list.handleInput(data);
150
+ tui.requestRender();
151
+ },
152
+ };
153
+ });
154
+ }
155
+
156
+ /** The file's object, `{}` if it doesn't exist, or undefined if it holds anything else (so it's never overwritten). */
157
+ function readRaw(file: string): Raw | undefined {
158
+ let parsed: unknown;
159
+ try {
160
+ parsed = JSON.parse(fs.readFileSync(file, "utf8"));
161
+ } catch (error) {
162
+ return (error as NodeJS.ErrnoException).code === "ENOENT" ? {} : undefined;
163
+ }
164
+ return isObject(parsed) ? parsed : undefined;
165
+ }
166
+
167
+ /** setup (`fromScratch`), or configure: edit the current values, or start over from a Preset when there's no file yet. */
168
+ async function guidedConfig(ctx: ExtensionCommandContext, fromScratch: boolean): Promise<void> {
169
+ const file = path.join(getAgentDir(), "pi-hud-plus.json");
170
+ const broken = `pi-hud-plus: ${file} isn't a JSON object. Fix or delete it, then run the command again.`;
171
+ const raw = readRaw(file);
172
+ if (!raw) return ctx.ui.notify(broken, "error");
173
+ const before = valuesFrom(mergeConfig(raw));
174
+ let start = before;
175
+ if (fromScratch || !fs.existsSync(file)) {
176
+ const overwrite = "Start over from a Preset? Colors, thresholds and other fields the list doesn't show are kept.";
177
+ if (fs.existsSync(file) && !(await ctx.ui.confirm("Overwrite pi-hud-plus config?", overwrite))) return;
178
+ const layout = await ctx.ui.select("HUD layout", LAYOUTS);
179
+ if (!layout) return;
180
+ const name = await ctx.ui.select("Starting Preset", PRESET_NAMES);
181
+ if (!name) return;
182
+ const language = await ctx.ui.select("HUD language", LANGUAGES);
183
+ if (!language) return;
184
+ start = { ...before, ...preset(name), layout, language, customLine: "" };
185
+ }
186
+ const after = await editValues(ctx, start);
187
+ if (!after) return;
188
+ const summary = changes(before, after);
189
+ if (!summary.length) return ctx.ui.notify("No changes", "info");
190
+ if (!(await ctx.ui.confirm("Save pi-hud-plus config?", summary.join("\n")))) return;
191
+ // Re-read: the file may have been edited while the list was open.
192
+ const latest = readRaw(file);
193
+ if (!latest) return ctx.ui.notify(broken, "error");
194
+ fs.writeFileSync(file, JSON.stringify(deepMerge(latest, toPatch(before, after)), null, 2) + "\n");
195
+ await ctx.reload();
196
+ }
197
+
198
+ export function registerCommands(pi: ExtensionAPI): void {
199
+ const commands = {
200
+ "pi-hud:setup": ["Set up the HUD: layout, Preset, language, then Elements", true],
201
+ "pi-hud:configure": ["Change the HUD's Elements, layout and language", false],
202
+ } as const;
203
+ for (const [name, [description, fromScratch]] of Object.entries(commands)) {
204
+ pi.registerCommand(name, {
205
+ description,
206
+ handler: async (_args, ctx) => {
207
+ // Same guard as the footer: the settings list needs pi's TUI.
208
+ if (!ctx.hasUI || ctx.mode !== "tui") return ctx.ui.notify(`pi-hud-plus: /${name} needs pi's interactive UI.`, "error");
209
+ await guidedConfig(ctx, fromScratch);
210
+ },
211
+ });
212
+ }
213
+ }
package/src/config.ts CHANGED
@@ -63,7 +63,7 @@ export interface HudConfig {
63
63
  showSeparators: boolean;
64
64
  pathLevels: 1 | 2 | 3;
65
65
  elementOrder: HudElement[];
66
- /** Shell command whose output is shown as an Extra command Line. "" = off. Ignored in the project file. */
66
+ /** Shell command whose output is shown as an Extra command Line. "" = off. */
67
67
  extraCommand: string;
68
68
  gitStatus: {
69
69
  enabled: boolean;
@@ -174,9 +174,9 @@ export const DEFAULT_CONFIG: HudConfig = {
174
174
  },
175
175
  };
176
176
 
177
- type Raw = Record<string, unknown>;
177
+ export type Raw = Record<string, unknown>;
178
178
 
179
- function isObject(value: unknown): value is Raw {
179
+ export function isObject(value: unknown): value is Raw {
180
180
  return typeof value === "object" && value !== null && !Array.isArray(value);
181
181
  }
182
182
 
@@ -351,7 +351,7 @@ export function mergeConfig(userConfig: unknown): HudConfig {
351
351
  }
352
352
 
353
353
  /** Objects merge recursively; arrays and scalars from `override` replace. */
354
- function deepMerge(base: Raw, override: Raw): Raw {
354
+ export function deepMerge(base: Raw, override: Raw): Raw {
355
355
  const merged: Raw = { ...base };
356
356
  for (const [key, value] of Object.entries(override)) {
357
357
  const current = merged[key];
@@ -370,10 +370,7 @@ function readJsonObject(file: string): Raw {
370
370
  }
371
371
  }
372
372
 
373
- /** Reads `<agentDir>/pi-hud-plus.json`, then deep-merges `<cwd>/.pi/pi-hud-plus.json` over it. */
374
- export function loadConfig(cwd: string, agentDir: string): HudConfig {
375
- const global = readJsonObject(path.join(agentDir, "pi-hud-plus.json"));
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));
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")));
379
376
  }
package/src/extra-cmd.ts CHANGED
@@ -24,8 +24,8 @@ export function sanitize(input: string): string {
24
24
  * Run the Extra command and parse its JSON output, expecting { label: string }.
25
25
  * Returns null on any error (timeout, non-zero exit, parse failure, missing label).
26
26
  *
27
- * SECURITY NOTE: cmd comes only from the user's global config; a project file's extraCommand is
28
- * stripped before merging, so opening a repo can't run commands.
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
29
  */
30
30
  export async function runExtraCmd(exec: Exec, cmd: string, timeout: number = TIMEOUT_MS): Promise<string | null> {
31
31
  try {
package/src/index.ts CHANGED
@@ -12,6 +12,7 @@ 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";
16
17
  import { runExtraCmd } from "./extra-cmd.ts";
17
18
  import { getGitStatus } from "./git.ts";
@@ -107,6 +108,7 @@ const DISPLACED_NOTICE =
107
108
 
108
109
  /** Pi adapter: owns the footer and keeps the cached HUD snapshot up to date. */
109
110
  export default function piHud(pi: ExtensionAPI): void {
111
+ registerCommands(pi);
110
112
  // Bumped on every session start/shutdown. Async work captures it and checks isLive(gen) before touching anything.
111
113
  let generation = 0;
112
114
  let session: Session | undefined;
@@ -215,7 +217,7 @@ export default function piHud(pi: ExtensionAPI): void {
215
217
 
216
218
  pi.on("session_start", (_event, ctx: ExtensionContext) => {
217
219
  if (!ctx.hasUI || ctx.mode !== "tui") return;
218
- const config = loadConfig(ctx.cwd, getAgentDir());
220
+ const config = loadConfig(getAgentDir());
219
221
  const breakdown = lastBreakdown(ctx.sessionManager.getEntries());
220
222
  const current: Session = (session = {
221
223
  generation: ++generation,
@@ -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
- // modelOverride can come from an untrusted project config.
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
 
package/src/sanitize.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  // eslint-disable-next-line no-control-regex
2
2
  const CONTROL_AND_BIDI_PATTERN = /[\u0000-\u001F\u007F-\u009F\u061C\u200E\u200F\u202A-\u202E\u2066-\u2069\u206A-\u206F]/g;
3
3
 
4
- /** Strips C0/C1 control and bidi characters so untrusted text (paths, names, a project config) can't inject escape codes. */
4
+ /** Strips C0/C1 control and bidi characters so untrusted text (paths, names, command output) can't inject escape codes. */
5
5
  export function sanitize(value: string): string {
6
6
  return value.replace(CONTROL_AND_BIDI_PATTERN, "");
7
7
  }