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 ADDED
@@ -0,0 +1,21 @@
1
+ # Changelog
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
+
13
+ ## [0.1.0] - 2026-11-14
14
+
15
+ ### New Features
16
+
17
+ - **claude-hud for pi**: replaces pi's footer with a claude-hud-style HUD. It shows the model badge with an optional thinking level, project path and git status, the context bar, prompt cache countdown, approximate RAM, the Environment line (AGENTS.md, skills, prompts, MCPs), the tools line, session times, session tokens, cost, speed and `pi vX`.
18
+ - **claude-hud config**: `~/.pi/agent/pi-hud-plus.json`, with a per-project override at `.pi/pi-hud-plus.json`. Field names match claude-hud's, so a pasted claude-hud config loads and unknown fields are ignored.
19
+ - **Extension statuses**: other extensions' footer statuses get their own dimmed Line.
20
+ - **Extra command**: `extraCommand` runs a shell command and shows its `{ "label": "..." }` output on the first Line.
21
+ - **Simplified Chinese**: `"language": "zh-Hans"`.
package/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Jarrod Watts (claude-hud)
4
+ Copyright (c) 2026 lkangd
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,212 @@
1
- # Temporary Holding Version
1
+ # pi-hud-plus
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A [claude-hud](https://github.com/jarrodwatts/claude-hud)-style HUD for [pi](https://pi.dev): it replaces pi's footer with model, context, git, tools, cache and session information, configured with claude-hud's field names.
4
+
5
+ ![pi-hud-plus HUD](https://raw.githubusercontent.com/lkangd/pi-hud-plus/main/docs/screenshot.png)
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ pi install npm:pi-hud-plus
11
+ ```
12
+
13
+ Or try it once without installing:
14
+
15
+ ```bash
16
+ pi -e npm:pi-hud-plus
17
+ ```
18
+
19
+ The HUD runs only in pi's interactive TUI. Print, JSON and RPC modes are left alone.
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
+
30
+ ## Lines and Elements
31
+
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 `…`.
33
+
34
+ | Element | What it shows | Toggled by |
35
+ |---|---|---|
36
+ | `project` | `[model]` badge, project path, `git:(branch* ↑2 ↓1 [+120 -14])`, then session name, `pi vX`, the Extra command's label, session duration, cost and output speed | `display.showModel`, `display.showProject`, `gitStatus.enabled`, `display.showSessionName`, `display.showVersion`, `extraCommand`, `display.showDuration`, `display.showCost`, `display.showSpeed` |
37
+ | `context` | `Context ██████░░░░ 46%`, coloured by the warning and critical thresholds. At or above the critical threshold it adds the latest reply's `(in: …, cache: …)` split | `display.showContextBar`, `display.contextValue`, `display.showTokenBreakdown` |
38
+ | `promptCache` | `Cache ⏱ 3m 45s`: time left on the prompt cache since the last reply, yellow near the end, then `expired` | `display.showPromptCache`, `display.promptCacheTtlSeconds` |
39
+ | `memory` | `Approx RAM ████░░ 12 GB / 16 GB (75%)`: system RAM. Expanded layout only | `display.showMemoryUsage` |
40
+ | `environment` | `2 AGENTS.md \| 5 skills \| 3 prompts \| 1 MCPs`: what shapes the agent's context. MCPs are the distinct `mcp__<server>__*` tool namespaces | `display.showConfigCounts`, `display.environmentThreshold` |
41
+ | `tools` | Up to two running tools with their target (`◐ bash: npm test`), then finished tools by count (`✓ read ×6`) | `display.showTools`, `display.toolNameMaxLength`, `display.toolsMaxVisible` |
42
+ | `sessionTime` | `Started: 42m ago │ Last reply: 1m ago` | `display.showSessionStartDate`, `display.showLastResponseAt`, `display.timeFormat` |
43
+
44
+ Two Lines aren't Elements and so aren't part of `elementOrder`:
45
+
46
+ - **Session tokens**: `Tokens 722k (in: 41k, out: 19k, cache: 662k)`, summed over the session the way pi's footer sums them. It comes after the Element Lines. Toggled by `display.showSessionTokens`.
47
+ - **Extension statuses**: other extensions' footer statuses, sorted by key, on one dimmed Line. It is always last. Toggled by `display.showExtensionStatuses`.
48
+
49
+ The **Custom line** (`display.customLine`) is static text that goes at the start or end of the `project` Line (the session Line in the compact layout), depending on `display.customLinePosition`.
50
+
51
+ With `"lineLayout": "compact"`, everything goes on one session Line (model badge, context, project and git, then the other enabled Elements), with the tools Line under it. Memory isn't shown, and `elementOrder` and `mergeGroups` don't apply.
52
+
53
+ `display.mergeGroups` joins Elements that sit next to each other in `elementOrder` onto one Line, separated by ` │ `, when they fit. For example, `[["context", "promptCache"]]`. `showSeparators` draws a rule above the tools Line.
54
+
55
+ ## Config
56
+
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.
58
+
59
+ The file is read when a session starts. After editing it, run `/reload`.
60
+
61
+ ### Field reference
62
+
63
+ Top level:
64
+
65
+ | Field | Default | Values |
66
+ |---|---|---|
67
+ | `language` | `"en"` | `"en"`, `"zh-Hans"` (`"zh"` is accepted as `"zh-Hans"`) |
68
+ | `lineLayout` | `"expanded"` | `"expanded"`, `"compact"` |
69
+ | `showSeparators` | `false` | boolean |
70
+ | `pathLevels` | `1` | `1`, `2`, `3`: how many trailing directories of the cwd to show |
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 |
72
+ | `extraCommand` | `""` (off) | shell command, see [Extra command](#extra-command) |
73
+
74
+ `gitStatus`:
75
+
76
+ | Field | Default | Values |
77
+ |---|---|---|
78
+ | `enabled` | `true` | boolean. When off, no git commands run |
79
+ | `showDirty` | `true` | boolean: `*` after the branch when the tree is dirty |
80
+ | `showAheadBehind` | `false` | boolean: `↑n ↓n` against the upstream |
81
+ | `showFileStats` | `false` | boolean: line diff `[+n -n]` (expanded) or file counts `!n +n ✘n ?n` (compact) |
82
+ | `branchOverflow` | `"truncate"` | `"truncate"` keeps project and git in one segment; `"wrap"` gives git its own segment |
83
+ | `pushWarningThreshold` | `0` (off) | colour `↑n` with `colors.warning` from this many unpushed commits |
84
+ | `pushCriticalThreshold` | `0` (off) | colour `↑n` with `colors.critical` from this many unpushed commits |
85
+
86
+ `display`:
87
+
88
+ | Field | Default | Values |
89
+ |---|---|---|
90
+ | `showModel` | `true` | boolean. The badge is prefixed with `provider/` when more than one provider is available, like pi's footer |
91
+ | `modelFormat` | `"full"` | `"full"`; `"compact"` strips a `(… context)` suffix; `"short"` also strips a leading `Claude ` |
92
+ | `modelOverride` | `""` | text shown instead of the model name (max 80 chars) |
93
+ | `showThinkingLevel` | `false` | boolean: `○ low`, `◔ medium`, `◑ high`, `◕ xhigh` in the badge |
94
+ | `showProject` | `true` | boolean |
95
+ | `showSessionName` | `false` | boolean |
96
+ | `showVersion` | `false` | boolean: `pi vX` |
97
+ | `showDuration` | `false` | boolean: `⏱️ 42m` since the session started |
98
+ | `showCost` | `false` | boolean: `Cost $1.87`, with `(sub)` on a subscription |
99
+ | `showSpeed` | `false` | boolean: `out: 61.4 tok/s` of the streaming reply |
100
+ | `showContextBar` | `true` | boolean. Off shows the value only |
101
+ | `contextValue` | `"percent"` | `"percent"`, `"tokens"` (`92k/200k`), `"remaining"`, `"both"` |
102
+ | `contextWarningThreshold` | `70` | 0–100 |
103
+ | `contextCriticalThreshold` | `85` | 0–100 |
104
+ | `showTokenBreakdown` | `true` | boolean: `(in: …, cache: …)` at or above the critical threshold |
105
+ | `showPromptCache` | `false` | boolean |
106
+ | `promptCacheTtlSeconds` | `300` | positive whole number |
107
+ | `showMemoryUsage` | `false` | boolean |
108
+ | `showConfigCounts` | `false` | boolean: the Environment line |
109
+ | `environmentThreshold` | `0` | hide the Environment line until the counts add up to this |
110
+ | `showTools` | `false` | boolean |
111
+ | `toolNameMaxLength` | `0` (no limit) | cut tool names to this many chars. When set, MCP tools show only their tool name |
112
+ | `toolsMaxVisible` | `4` | how many finished tools to list; `0` lists all |
113
+ | `showSessionStartDate` | `false` | boolean |
114
+ | `showLastResponseAt` | `false` | boolean |
115
+ | `timeFormat` | `"relative"` | `"relative"` (`3m ago`), `"absolute"` (`2026-11-14 09:30`), `"both"`; `"elapsed"` and `"elapsedAndAbsolute"` read like `"relative"` and `"both"` |
116
+ | `showSessionTokens` | `false` | boolean |
117
+ | `showExtensionStatuses` | `true` | boolean |
118
+ | `mergeGroups` | `[]` | arrays of at least two Elements, e.g. `[["context", "promptCache"]]` |
119
+ | `customLine` | `""` | static text (max 80 chars) |
120
+ | `customLinePosition` | `"last"` | `"first"`, `"last"` |
121
+
122
+ `colors`: each value is a name (`"dim"`, `"red"`, `"green"`, `"yellow"`, `"magenta"`, `"cyan"`, `"brightBlue"`, `"brightMagenta"`), a 256-colour index (`0`–`255`) or a hex string (`"#rrggbb"`).
123
+
124
+ | Field | Default | Colours |
125
+ |---|---|---|
126
+ | `context` | `"green"` | context value and bar below the warning threshold |
127
+ | `warning` | `"yellow"` | context at or above the warning threshold, cache about to expire |
128
+ | `critical` | `"red"` | context at or above the critical threshold |
129
+ | `model` | `"cyan"` | model badge |
130
+ | `project` | `"yellow"` | project path |
131
+ | `git` | `"magenta"` | `git:(` `)` |
132
+ | `gitBranch` | `"cyan"` | branch and ahead/behind |
133
+ | `label` | `"dim"` | labels and secondary text |
134
+ | `custom` | `208` | Custom line |
135
+ | `barFilled` | `"█"` | one character for the filled part of the bars |
136
+ | `barEmpty` | `"░"` | one character for the empty part of the bars |
137
+
138
+ ### Example
139
+
140
+ `~/.pi/agent/pi-hud-plus.json`:
141
+
142
+ ```json
143
+ {
144
+ "pathLevels": 2,
145
+ "gitStatus": {
146
+ "showAheadBehind": true,
147
+ "showFileStats": true
148
+ },
149
+ "display": {
150
+ "showThinkingLevel": true,
151
+ "showCost": true,
152
+ "showTools": true,
153
+ "showPromptCache": true,
154
+ "showConfigCounts": true,
155
+ "showSessionTokens": true,
156
+ "mergeGroups": [["context", "promptCache"]]
157
+ },
158
+ "colors": {
159
+ "model": "#a78bfa",
160
+ "barFilled": "■",
161
+ "barEmpty": "□"
162
+ }
163
+ }
164
+ ```
165
+
166
+ Then run `/reload`.
167
+
168
+ ## Extra command
169
+
170
+ `extraCommand` runs a shell command (`sh -c`) and shows its label on the `project` Line, or near the end of the compact Line. The command must exit 0 and print JSON with a `label` string:
171
+
172
+ ```json
173
+ { "extraCommand": "echo '{\"label\": \"on-call: alice\"}'" }
174
+ ```
175
+
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.
177
+
178
+ ## Coexisting with other footer extensions
179
+
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.
181
+
182
+ If another footer extension (for example pi-powerbar) takes the footer, pi-hud-plus steps aside. It hides and stops its background work until the next session starts. It also warns once per pi process:
183
+
184
+ > pi-hud-plus: another extension took over pi's footer, so the HUD is hidden. Disable that extension (e.g. pi-powerbar, via `pi config`) to see the HUD.
185
+
186
+ To see the HUD, disable the other footer extension with `pi config`, then start a new session or run `/reload`.
187
+
188
+ ## Language
189
+
190
+ `"language": "zh-Hans"` switches the HUD's labels to Simplified Chinese (`上下文`, `3m前`, …). `"zh"` works too. The default is `"en"`. The language is set only in config; pi-hud-plus doesn't detect your locale.
191
+
192
+ ## Differences from claude-hud
193
+
194
+ - **No usage limits**: there's no 5h/7d subscription usage, and no external usage snapshots, because pi has no API for them. Every usage field (`showUsage`, `usageValue`, `usageBarEnabled`, `sevenDayThreshold`, `externalUsage*`, `colors.usage`, …) is ignored.
195
+ - **Dropped Elements**: `addedDirs`, `usage`, `agents` and `todos` have no pi equivalent. The output style and Claude Code's mode line are gone too.
196
+ - **Pi equivalents**: `pi vX` instead of `CC vX`; pi's thinking level instead of Claude's effort level; the Environment line counts AGENTS.md files, skills, prompt templates and MCP servers instead of CLAUDE.md, rules, MCPs and hooks.
197
+ - **Renamed fields, no aliases**: `display.showClaudeCodeVersion` is `display.showVersion`, and `display.showEffortLevel` is `display.showThinkingLevel`.
198
+ - **Other dropped fields**: `maxWidth` and `forceMaxWidth` (pi gives the HUD its width), `display.showAddedDirs`, `addedDirsLayout`, `showAgents`, `showTodos`, `showOutputStyle` and `autocompactBuffer`.
199
+ - **Changed defaults**: `mergeGroups` defaults to `[]`, and `elementOrder` has no `usage`, `agents`, `todos` or `addedDirs`.
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`.
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.
203
+ - **No branch link**: claude-hud links the branch name to its remote (`branchUrl`) with a terminal hyperlink; pi-hud-plus shows plain text.
204
+ - **`max` thinking level**: pi's `max` level, which claude-hud has no equivalent for, shows as `◕` like `xhigh`.
205
+ - **Chinese relative times**: keep claude-hud's unit style, so `3m前`, not `3分钟前`.
206
+ - A pasted claude-hud config still loads: fields that are unknown or have been dropped are ignored.
207
+
208
+ ## Credits and license
209
+
210
+ pi-hud-plus is a port of [claude-hud](https://github.com/jarrodwatts/claude-hud) by Jarrod Watts. The render code, colours, layouts, config fields and most of the tests come from it.
211
+
212
+ [MIT](LICENSE). Copyright Jarrod Watts (claude-hud) and lkangd.
package/package.json CHANGED
@@ -1,6 +1,49 @@
1
1
  {
2
2
  "name": "pi-hud-plus",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "A claude-hud-style HUD for pi's footer",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "author": "lkangd",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/lkangd/pi-hud-plus.git"
11
+ },
12
+ "homepage": "https://github.com/lkangd/pi-hud-plus#readme",
13
+ "bugs": {
14
+ "url": "https://github.com/lkangd/pi-hud-plus/issues"
15
+ },
16
+ "keywords": [
17
+ "pi-package",
18
+ "pi-extension",
19
+ "hud",
20
+ "statusline"
21
+ ],
22
+ "files": [
23
+ "src",
24
+ "README.md",
25
+ "CHANGELOG.md"
26
+ ],
27
+ "pi": {
28
+ "extensions": [
29
+ "./src/index.ts"
30
+ ],
31
+ "image": "https://raw.githubusercontent.com/lkangd/pi-hud-plus/main/docs/screenshot.png"
32
+ },
33
+ "scripts": {
34
+ "typecheck": "tsc --noEmit",
35
+ "test": "node --test --import tsx 'test/*.test.ts'",
36
+ "prepublishOnly": "npm run typecheck && npm test"
37
+ },
38
+ "peerDependencies": {
39
+ "@earendil-works/pi-coding-agent": "*",
40
+ "@earendil-works/pi-tui": "*"
41
+ },
42
+ "devDependencies": {
43
+ "@earendil-works/pi-coding-agent": "^1.5.2",
44
+ "@earendil-works/pi-tui": "^1.5.2",
45
+ "@types/node": "^22.20.5",
46
+ "tsx": "^4.23.15",
47
+ "typescript": "^5.9.3"
48
+ }
49
+ }
package/src/clock.ts ADDED
@@ -0,0 +1,14 @@
1
+ import type { HudConfig } from "./config.ts";
2
+
3
+ /** Whether any enabled Element changes with time alone, so the HUD needs the clock. Add new ticking Elements here. */
4
+ export function hasTickingElement({ display }: HudConfig): boolean {
5
+ const relativeTimes = display.timeFormat !== "absolute" && (display.showSessionStartDate || display.showLastResponseAt);
6
+ return display.showDuration || relativeTimes || display.showPromptCache || display.showMemoryUsage;
7
+ }
8
+
9
+ /** A 1s clock that doesn't keep pi alive. Returns its stop function. */
10
+ export function startClock(onTick: (now: number) => void): () => void {
11
+ const timer = setInterval(() => onTick(Date.now()), 1000);
12
+ timer.unref();
13
+ return () => clearInterval(timer);
14
+ }
@@ -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
+ }