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 CHANGED
@@ -1,5 +1,27 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.3.0] - 2026-11-18
4
+
5
+ ### New Features
6
+
7
+ - **Usage limits**: the `usage` Element is back, with claude-hud's config fields. It shows 5h, Weekly and Monthly Limit windows for Codex (ChatGPT) and GLM Coding Plan models, and a Balance for DeepSeek models. The HUD fetches these from each vendor with pi's credentials. Other vendors can feed it through claude-hud's External usage snapshot file (`display.externalUsagePath`). The Element is on by default and sits beside the context bar. To stop the requests, set `display.showUsage` to `false` or turn off the new "Usage limits" row in `/pi-hud:configure`.
8
+ - **Git files Line**: with `gitStatus.showFileStats`, the expanded layout ends with up to 6 changed files, newest first, each linked when inside the project. The branch name links to its GitHub tree page.
9
+ - **Debug logging**: start pi with `DEBUG=pi-hud-plus` to log why the Extra command, a Usage limit request or the config file failed, to `~/.pi/agent/pi-hud-plus-debug.log`.
10
+
11
+ ### Bug Fixes
12
+
13
+ - **Speed**: the output speed now hides when a reply stalls for more than 2 seconds, as in claude-hud, instead of staying until the reply ends.
14
+
15
+ ## [0.2.0] - 2026-11-17
16
+
17
+ ### New Features
18
+
19
+ - **`/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.
20
+
21
+ ### Breaking Changes
22
+
23
+ - **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`.
24
+
3
25
  ## [0.1.0] - 2026-11-14
4
26
 
5
27
  ### 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 `…`.
@@ -26,6 +35,7 @@ The default `lineLayout` is `"expanded"`: one Line per Element, in `elementOrder
26
35
  |---|---|---|
27
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` |
28
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
+ | `usage` | `Usage ██░░░░ 25% (resets in 1h 30m)`: the 5h Limit window, plus `\| Weekly …` and `\| Monthly …` at or above `sevenDayThreshold`, or a Balance (`Usage ¥4.12`). Fetched for Codex, GLM Coding Plan and DeepSeek models, otherwise read from the External usage snapshot file. See [Usage limits](#usage-limits) | `display.showUsage`, `display.usageValue`, `display.usageBarEnabled`, `display.showResetLabel`, `display.usageCompact`, `display.usageThreshold`, `display.sevenDayThreshold`, `display.externalUsagePath` |
29
39
  | `promptCache` | `Cache ⏱ 3m 45s`: time left on the prompt cache since the last reply, yellow near the end, then `expired` | `display.showPromptCache`, `display.promptCacheTtlSeconds` |
30
40
  | `memory` | `Approx RAM ████░░ 12 GB / 16 GB (75%)`: system RAM. Expanded layout only | `display.showMemoryUsage` |
31
41
  | `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,18 +51,13 @@ The **Custom line** (`display.customLine`) is static text that goes at the start
41
51
 
42
52
  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.
43
53
 
44
- `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
+ `display.mergeGroups` joins Elements that sit next to each other in `elementOrder` onto one Line, separated by ` │ `, when they fit. The default `[["context", "usage"]]` puts usage beside the context bar. `showSeparators` draws a rule above the tools Line.
45
55
 
46
56
  ## Config
47
57
 
48
- pi-hud-plus reads two JSON files:
49
-
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.
58
+ 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.
54
59
 
55
- The files are read when a session starts. After editing one, run `/reload`.
60
+ The file is read when a session starts. After editing it, run `/reload`.
56
61
 
57
62
  ### Field reference
58
63
 
@@ -64,8 +69,8 @@ Top level:
64
69
  | `lineLayout` | `"expanded"` | `"expanded"`, `"compact"` |
65
70
  | `showSeparators` | `false` | boolean |
66
71
  | `pathLevels` | `1` | `1`, `2`, `3`: how many trailing directories of the cwd to show |
67
- | `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
+ | `elementOrder` | `["project", "context", "usage", "promptCache", "memory", "environment", "tools", "sessionTime"]` | Elements in Line order. Leaving an Element out hides its Line. Unknown ids and duplicates are dropped |
73
+ | `extraCommand` | `""` (off) | shell command, see [Extra command](#extra-command) |
69
74
 
70
75
  `gitStatus`:
71
76
 
@@ -74,7 +79,7 @@ Top level:
74
79
  | `enabled` | `true` | boolean. When off, no git commands run |
75
80
  | `showDirty` | `true` | boolean: `*` after the branch when the tree is dirty |
76
81
  | `showAheadBehind` | `false` | boolean: `↑n ↓n` against the upstream |
77
- | `showFileStats` | `false` | boolean: line diff `[+n -n]` (expanded) or file counts `!n +n ✘n ?n` (compact) |
82
+ | `showFileStats` | `false` | boolean: line diff `[+n -n]` plus a last Line listing up to 6 changed files, newest first (expanded), or file counts `!n +n ✘n ?n` (compact) |
78
83
  | `branchOverflow` | `"truncate"` | `"truncate"` keeps project and git in one segment; `"wrap"` gives git its own segment |
79
84
  | `pushWarningThreshold` | `0` (off) | colour `↑n` with `colors.warning` from this many unpushed commits |
80
85
  | `pushCriticalThreshold` | `0` (off) | colour `↑n` with `colors.critical` from this many unpushed commits |
@@ -98,6 +103,15 @@ Top level:
98
103
  | `contextWarningThreshold` | `70` | 0–100 |
99
104
  | `contextCriticalThreshold` | `85` | 0–100 |
100
105
  | `showTokenBreakdown` | `true` | boolean: `(in: …, cache: …)` at or above the critical threshold |
106
+ | `showUsage` | `true` | boolean |
107
+ | `usageValue` | `"percent"` | `"percent"` used, `"remaining"` |
108
+ | `usageBarEnabled` | `true` | boolean |
109
+ | `showResetLabel` | `true` | boolean: `resets in` before the reset time |
110
+ | `usageCompact` | `false` | boolean: `5h: 25% (1h 30m)` |
111
+ | `usageThreshold` | `0` | 0–100: hide usage until 5h or Weekly reaches this |
112
+ | `sevenDayThreshold` | `80` | 0–100: show Weekly and Monthly at or above this (`0` = always) |
113
+ | `externalUsagePath` | `""` | path of an External usage snapshot file in claude-hud's format |
114
+ | `externalUsageFreshnessMs` | `300000` | ignore the snapshot once its `updated_at` is older than this |
101
115
  | `showPromptCache` | `false` | boolean |
102
116
  | `promptCacheTtlSeconds` | `300` | positive whole number |
103
117
  | `showMemoryUsage` | `false` | boolean |
@@ -111,7 +125,7 @@ Top level:
111
125
  | `timeFormat` | `"relative"` | `"relative"` (`3m ago`), `"absolute"` (`2026-11-14 09:30`), `"both"`; `"elapsed"` and `"elapsedAndAbsolute"` read like `"relative"` and `"both"` |
112
126
  | `showSessionTokens` | `false` | boolean |
113
127
  | `showExtensionStatuses` | `true` | boolean |
114
- | `mergeGroups` | `[]` | arrays of at least two Elements, e.g. `[["context", "promptCache"]]` |
128
+ | `mergeGroups` | `[["context", "usage"]]` | arrays of at least two Elements; `[]` turns merging off |
115
129
  | `customLine` | `""` | static text (max 80 chars) |
116
130
  | `customLinePosition` | `"last"` | `"first"`, `"last"` |
117
131
 
@@ -120,6 +134,8 @@ Top level:
120
134
  | Field | Default | Colours |
121
135
  |---|---|---|
122
136
  | `context` | `"green"` | context value and bar below the warning threshold |
137
+ | `usage` | `"brightBlue"` | usage below 75% |
138
+ | `usageWarning` | `"brightMagenta"` | usage at 75% or more (90% and up is `critical`) |
123
139
  | `warning` | `"yellow"` | context at or above the warning threshold, cache about to expire |
124
140
  | `critical` | `"red"` | context at or above the critical threshold |
125
141
  | `model` | `"cyan"` | model badge |
@@ -169,9 +185,43 @@ Then run `/reload`.
169
185
  { "extraCommand": "echo '{\"label\": \"on-call: alice\"}'" }
170
186
  ```
171
187
 
172
- 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.
188
+ 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. To see why, use [debug logging](#debug-logging).
189
+
190
+ ## Usage limits
191
+
192
+ The `usage` Element follows the current model. pi-hud-plus recognises the vendor from the model itself (its API and base URL), not the provider's name, so renamed and custom providers work too.
193
+
194
+ | Vendor | Detected by | Shows | From |
195
+ |---|---|---|---|
196
+ | Codex (ChatGPT subscription) | the model's API is `openai-codex-responses` | 5h and Weekly Limit windows (a plan may report only one of them) | the `codex.rate_limits` frame ChatGPT sends with each reply, else `GET https://chatgpt.com/backend-api/wham/usage` |
197
+ | GLM Coding Plan | base URL host `open.bigmodel.cn`, `bigmodel.cn` or `api.z.ai` | 5h, Weekly (missing on some plans) and Monthly (tool calls) | `GET https://open.bigmodel.cn/api/monitor/usage/quota/limit`, or the same path on `api.z.ai` |
198
+ | DeepSeek | base URL host `api.deepseek.com` | a Balance per currency, e.g. `¥4.12` | `GET https://api.deepseek.com/user/balance` |
199
+
200
+ The HUD sends these requests itself, with the API key or token pi already has for the model. It gets them from pi's model registry, so pi keeps OAuth tokens refreshed, and it never reads `auth.json`. Each request goes only to that model's own vendor. The Codex endpoint and frame are unofficial ChatGPT internals, and GLM documents its endpoint only in Zhipu's own plugins, so either may change without notice. DeepSeek's endpoint is public API. The `api.z.ai` host hasn't been tested against a live account.
201
+
202
+ It refreshes when a session starts, when you switch models, after each agent run and every 5 minutes. Only one request runs at a time, and none is sent within a minute of the last request or Codex frame, so a vendor that's down gets at most one request a minute (a failed request hides the Element). A Codex reply's frame updates the Element right away, so the request after that reply is usually skipped, and a request already running when a frame arrives is ignored. Each request times out after 10 seconds. Switching to another vendor's model, or to a model on another host (GLM's `open.bigmodel.cn` and `api.z.ai` are separate accounts), clears the Element until the new data arrives. With `display.showUsage` off, no requests are sent.
203
+
204
+ A failed request (no credentials, a timeout, an HTTP error, a reply in an unexpected shape) shows no error. Instead, the Element shows the External usage snapshot, or hides until a later refresh succeeds. To see why the request failed, use [debug logging](#debug-logging).
205
+
206
+ ### External usage snapshot
207
+
208
+ For any other vendor, or when a vendor's request fails, the HUD can read a JSON file that your own script keeps up to date. Set its path in `display.externalUsagePath`. The format is claude-hud's:
209
+
210
+ ```json
211
+ {
212
+ "updated_at": "2026-11-18T09:30:00Z",
213
+ "five_hour": { "used_percentage": 45, "resets_at": "2026-11-18T12:00:00Z" },
214
+ "seven_day": { "used_percentage": 82, "resets_at": 1795000000 },
215
+ "balance_label": "$12.40"
216
+ }
217
+ ```
218
+
219
+ - `updated_at` is required: an ISO date string, or epoch seconds or milliseconds (numbers above 10¹² count as milliseconds). Once it's older than `display.externalUsageFreshnessMs` (5 minutes by default), the file is ignored.
220
+ - `five_hour`, `seven_day` and `balance_label` are each optional, but at least one must be present. `used_percentage` is 0–100, rounded and clamped. `resets_at` takes the same forms as `updated_at`. If a `resets_at` doesn't parse, the whole file is ignored.
221
+ - `balance_label` is shown instead of the windows. Control and escape characters are stripped, and it is cut to 50 characters.
222
+ - The format has no monthly window.
173
223
 
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`.
224
+ The file is read only while the current model has no data of its own: on the refresh triggers above and on every 1-second clock tick. pi-hud-plus never writes it.
175
225
 
176
226
  ## Coexisting with other footer extensions
177
227
 
@@ -183,22 +233,29 @@ If another footer extension (for example pi-powerbar) takes the footer, pi-hud-p
183
233
 
184
234
  To see the HUD, disable the other footer extension with `pi config`, then start a new session or run `/reload`.
185
235
 
236
+ ## Debug logging
237
+
238
+ Start pi with `DEBUG=pi-hud-plus` (or `DEBUG=*`) to log why the Extra command failed, why a Usage limit request failed, or why the config file was ignored. Lines go to `~/.pi/agent/pi-hud-plus-debug.log`, not the terminal, because pi owns it.
239
+
186
240
  ## Language
187
241
 
188
242
  `"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.
189
243
 
190
244
  ## Differences from claude-hud
191
245
 
192
- - **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.
193
- - **Dropped Elements**: `addedDirs`, `usage`, `agents` and `todos` have no pi equivalent. The output style and Claude Code's mode line are gone too.
246
+ - **Usage limits**: pi has no API for them, so the HUD fetches them itself for the current model's vendor (Codex, the GLM Coding Plan or DeepSeek), using pi's credentials. See [Usage limits](#usage-limits). For any other model, it reads the External usage snapshot file (`externalUsagePath`), as claude-hud does.
247
+ - **Monthly**: a third Limit window, `Monthly` (`本月`), after Weekly. It comes from GLM's monthly tool-call pool and, like Weekly, is shown at or above `sevenDayThreshold`. In compact form it is `mo:`.
248
+ - **Balance for DeepSeek**: fetched from DeepSeek's API. In claude-hud a Balance comes only from the snapshot's `balance_label`.
249
+ - **No `externalUsageWritePath`**: it copies Claude Code's statusline data, which pi doesn't have.
250
+ - **`sevenDayThreshold` default**: an absent `sevenDayThreshold` is `80`, its documented default; claude-hud's validation turns it into `0`.
251
+ - **Dropped Elements**: `addedDirs`, `agents` and `todos` have no pi equivalent. The output style and Claude Code's mode line are gone too.
194
252
  - **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.
195
253
  - **Renamed fields, no aliases**: `display.showClaudeCodeVersion` is `display.showVersion`, and `display.showEffortLevel` is `display.showThinkingLevel`.
196
254
  - **Other dropped fields**: `maxWidth` and `forceMaxWidth` (pi gives the HUD its width), `display.showAddedDirs`, `addedDirsLayout`, `showAgents`, `showTodos`, `showOutputStyle` and `autocompactBuffer`.
197
- - **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
- - **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
- - **No branch link**: claude-hud links the branch name to its remote (`branchUrl`) with a terminal hyperlink; pi-hud-plus shows plain text.
255
+ - **Changed defaults**: `elementOrder` has no `agents`, `todos` or `addedDirs`. It keeps claude-hud's `usage` after `context`, and `mergeGroups` keeps claude-hud's `[["context", "usage"]]`.
256
+ - **New fields**: `extraCommand` (claude-hud's `--extra-cmd`, now config) and `display.showExtensionStatuses`.
257
+ - **Debug log**: `DEBUG=pi-hud-plus` instead of `DEBUG=claude-hud`, written to a file instead of stderr.
258
+ - **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
259
  - **`max` thinking level**: pi's `max` level, which claude-hud has no equivalent for, shows as `◕` like `xhigh`.
203
260
  - **Chinese relative times**: keep claude-hud's unit style, so `3m前`, not `3分钟前`.
204
261
  - A pasted claude-hud config still loads: fields that are unknown or have been dropped are ignored.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-hud-plus",
3
- "version": "0.1.0",
3
+ "version": "0.3.0",
4
4
  "description": "A claude-hud-style HUD for pi's footer",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/src/clock.ts CHANGED
@@ -1,9 +1,12 @@
1
1
  import type { HudConfig } from "./config.ts";
2
2
 
3
3
  /** Whether any enabled Element changes with time alone, so the HUD needs the clock. Add new ticking Elements here. */
4
+ // A native Usage limit's reset countdown depends on the data, not the config: that rule lives in syncClock (index.ts).
4
5
  export function hasTickingElement({ display }: HudConfig): boolean {
5
6
  const relativeTimes = display.timeFormat !== "absolute" && (display.showSessionStartDate || display.showLastResponseAt);
6
- return display.showDuration || relativeTimes || display.showPromptCache || display.showMemoryUsage;
7
+ // Usage: reset countdowns, and the External usage snapshot is re-read each tick for freshness.
8
+ const usage = display.showUsage && display.externalUsagePath !== "";
9
+ return display.showDuration || relativeTimes || display.showPromptCache || display.showMemoryUsage || usage;
7
10
  }
8
11
 
9
12
  /** A 1s clock that doesn't keep pi alive. Returns its stop function. */
@@ -0,0 +1,215 @@
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
+ ["showUsage", "Usage limits"],
17
+ ["showSpeed", "Output speed"],
18
+ ["showDuration", "Session duration"],
19
+ ["showSessionName", "Session name"],
20
+ ["showSessionTokens", "Session tokens"],
21
+ ["showCost", "Cost"],
22
+ ["showThinkingLevel", "Thinking level"],
23
+ ["showVersion", "Version"],
24
+ ["showMemoryUsage", "Memory"],
25
+ ["showPromptCache", "Prompt cache"],
26
+ ["showExtensionStatuses", "Extension statuses"],
27
+ ["showSessionStartDate", "Session start date"],
28
+ ["showLastResponseAt", "Last response time"],
29
+ ];
30
+
31
+ const LAYOUTS = ["expanded", "compact", "compact+separators"];
32
+ const LANGUAGES = ["en", "zh-Hans"];
33
+ // claude-hud's Git Style Mapping, plus off.
34
+ const GIT_STYLES: Record<string, Partial<HudConfig["gitStatus"]>> = {
35
+ off: { enabled: false },
36
+ branch: { enabled: true, showDirty: false, showAheadBehind: false, showFileStats: false },
37
+ "branch+dirty": { enabled: true, showDirty: true, showAheadBehind: false, showFileStats: false },
38
+ full: { enabled: true, showDirty: true, showAheadBehind: true, showFileStats: false },
39
+ "file stats": { enabled: true, showDirty: true, showAheadBehind: false, showFileStats: true },
40
+ };
41
+ const PRESET_NAMES = ["Full", "Essential", "Minimal"];
42
+
43
+ /** The settings-list rows in display order; rows with `values` cycle through them. */
44
+ const ROWS: { id: string; label: string; values?: string[] }[] = [
45
+ { id: "layout", label: "Layout", values: LAYOUTS },
46
+ { id: "language", label: "Language", values: LANGUAGES },
47
+ { id: "git", label: "Git", values: Object.keys(GIT_STYLES) },
48
+ ...TOGGLES.map(([id, label]) => ({ id, label, values: ["on", "off"] })),
49
+ { id: "customLine", label: "Custom line" },
50
+ ];
51
+ const RESET_ROW = "Reset to preset";
52
+
53
+ function gitStyle(git: HudConfig["gitStatus"]): string {
54
+ if (!git.enabled) return "off";
55
+ if (git.showFileStats) return "file stats";
56
+ if (git.showAheadBehind) return "full";
57
+ return git.showDirty ? "branch+dirty" : "branch";
58
+ }
59
+
60
+ function valuesFrom(config: HudConfig): Values {
61
+ return {
62
+ layout: config.lineLayout === "compact" ? (config.showSeparators ? "compact+separators" : "compact") : "expanded",
63
+ language: config.language,
64
+ git: gitStyle(config.gitStatus),
65
+ ...Object.fromEntries(TOGGLES.map(([key]) => [key, config.display[key] ? "on" : "off"])),
66
+ customLine: config.display.customLine,
67
+ };
68
+ }
69
+
70
+ /** A Preset's rows: the Elements and git style, never layout, language or the Custom line. */
71
+ function preset(name: string): Values {
72
+ const minimal = valuesFrom(DEFAULT_CONFIG);
73
+ delete minimal.layout;
74
+ delete minimal.language;
75
+ delete minimal.customLine;
76
+ if (name === "Full") return { ...minimal, ...Object.fromEntries(TOGGLES.map(([key]) => [key, "on"])) };
77
+ if (name === "Essential") return { ...minimal, showTools: "on", showUsage: "on", showDuration: "on", showExtensionStatuses: "on" };
78
+ // Minimal is the defaults except Usage limits, which is on by default but off in Minimal.
79
+ return { ...minimal, showUsage: "off" };
80
+ }
81
+
82
+ /** Only rows that changed are written, so a value the guided rows can't express (e.g. separators in expanded) survives. */
83
+ function toPatch(before: Values, after: Values): Raw {
84
+ const display: Raw = {};
85
+ const patch: Raw = { display };
86
+ for (const { id } of ROWS) {
87
+ const value = after[id]!;
88
+ if (value === before[id]) continue;
89
+ if (id === "layout") Object.assign(patch, { lineLayout: value === "expanded" ? "expanded" : "compact", showSeparators: value === "compact+separators" });
90
+ else if (id === "language") patch.language = value;
91
+ else if (id === "git") patch.gitStatus = GIT_STYLES[value];
92
+ else if (id === "customLine") display.customLine = value;
93
+ else display[id] = value === "on";
94
+ }
95
+ if (!Object.keys(display).length) delete patch.display;
96
+ return patch;
97
+ }
98
+
99
+ function changes(before: Values, after: Values): string[] {
100
+ const shown = (value: string) => value || "(none)";
101
+ return ROWS.filter(({ id }) => before[id] !== after[id]).map(({ id, label }) => `${label}: ${shown(before[id]!)} → ${shown(after[id]!)}`);
102
+ }
103
+
104
+ /** A one-line text prompt; Enter closes with the sanitized text, Esc closes without a value. */
105
+ function textInput(title: string, close: (value?: string) => void): Component {
106
+ const input = new Input();
107
+ input.onSubmit = (value) => close(sanitize(value).trim().slice(0, 80));
108
+ input.onEscape = () => close();
109
+ return {
110
+ render: (width) => [title, ...input.render(width)],
111
+ invalidate: () => input.invalidate(),
112
+ handleInput: (data) => input.handleInput(data),
113
+ };
114
+ }
115
+
116
+ function editValues(ctx: ExtensionCommandContext, start: Values): Promise<Values | undefined> {
117
+ return ctx.ui.custom<Values | undefined>((tui, theme, _kb, done) => {
118
+ const values = { ...start };
119
+ const items: SettingItem[] = ROWS.map((row) => ({ ...row, currentValue: values[row.id]! }));
120
+ items.find((item) => item.id === "customLine")!.submenu = (_current, close) => textInput("Custom line (empty removes it, Esc keeps it):", close);
121
+ items.push({
122
+ id: RESET_ROW,
123
+ label: RESET_ROW,
124
+ currentValue: "",
125
+ description: "Set every Element row and Git to a Preset's values; layout, language and the Custom line stay.",
126
+ submenu: (_current, close) => {
127
+ const presets = new SelectList(PRESET_NAMES.map((name) => ({ value: name, label: name })), PRESET_NAMES.length, getSelectListTheme());
128
+ presets.onSelect = ({ value }) => {
129
+ for (const [id, presetValue] of Object.entries(preset(value))) {
130
+ values[id] = presetValue;
131
+ list.updateValue(id, presetValue);
132
+ }
133
+ close();
134
+ };
135
+ presets.onCancel = () => close();
136
+ return presets;
137
+ },
138
+ });
139
+ const list = new SettingsList(
140
+ items,
141
+ Math.min(items.length, 15),
142
+ getSettingsListTheme(),
143
+ (id, value) => (values[id] = value),
144
+ () => done(values),
145
+ );
146
+ return {
147
+ // The list's own hint says "Esc to cancel"; here Esc ends editing and the save is confirmed next.
148
+ render: (width: number) => [theme.fg("accent", theme.bold("pi-hud-plus · Esc when done, then confirm to save")), "", ...list.render(width)],
149
+ invalidate: () => list.invalidate(),
150
+ handleInput(data: string) {
151
+ list.handleInput(data);
152
+ tui.requestRender();
153
+ },
154
+ };
155
+ });
156
+ }
157
+
158
+ /** The file's object, `{}` if it doesn't exist, or undefined if it holds anything else (so it's never overwritten). */
159
+ function readRaw(file: string): Raw | undefined {
160
+ let parsed: unknown;
161
+ try {
162
+ parsed = JSON.parse(fs.readFileSync(file, "utf8"));
163
+ } catch (error) {
164
+ return (error as NodeJS.ErrnoException).code === "ENOENT" ? {} : undefined;
165
+ }
166
+ return isObject(parsed) ? parsed : undefined;
167
+ }
168
+
169
+ /** setup (`fromScratch`), or configure: edit the current values, or start over from a Preset when there's no file yet. */
170
+ async function guidedConfig(ctx: ExtensionCommandContext, fromScratch: boolean): Promise<void> {
171
+ const file = path.join(getAgentDir(), "pi-hud-plus.json");
172
+ const broken = `pi-hud-plus: ${file} isn't a JSON object. Fix or delete it, then run the command again.`;
173
+ const raw = readRaw(file);
174
+ if (!raw) return ctx.ui.notify(broken, "error");
175
+ const before = valuesFrom(mergeConfig(raw));
176
+ let start = before;
177
+ if (fromScratch || !fs.existsSync(file)) {
178
+ const overwrite = "Start over from a Preset? Colors, thresholds and other fields the list doesn't show are kept.";
179
+ if (fs.existsSync(file) && !(await ctx.ui.confirm("Overwrite pi-hud-plus config?", overwrite))) return;
180
+ const layout = await ctx.ui.select("HUD layout", LAYOUTS);
181
+ if (!layout) return;
182
+ const name = await ctx.ui.select("Starting Preset", PRESET_NAMES);
183
+ if (!name) return;
184
+ const language = await ctx.ui.select("HUD language", LANGUAGES);
185
+ if (!language) return;
186
+ start = { ...before, ...preset(name), layout, language, customLine: "" };
187
+ }
188
+ const after = await editValues(ctx, start);
189
+ if (!after) return;
190
+ const summary = changes(before, after);
191
+ if (!summary.length) return ctx.ui.notify("No changes", "info");
192
+ if (!(await ctx.ui.confirm("Save pi-hud-plus config?", summary.join("\n")))) return;
193
+ // Re-read: the file may have been edited while the list was open.
194
+ const latest = readRaw(file);
195
+ if (!latest) return ctx.ui.notify(broken, "error");
196
+ fs.writeFileSync(file, JSON.stringify(deepMerge(latest, toPatch(before, after)), null, 2) + "\n");
197
+ await ctx.reload();
198
+ }
199
+
200
+ export function registerCommands(pi: ExtensionAPI): void {
201
+ const commands = {
202
+ "pi-hud:setup": ["Set up the HUD: layout, Preset, language, then Elements", true],
203
+ "pi-hud:configure": ["Change the HUD's Elements, layout and language", false],
204
+ } as const;
205
+ for (const [name, [description, fromScratch]] of Object.entries(commands)) {
206
+ pi.registerCommand(name, {
207
+ description,
208
+ handler: async (_args, ctx) => {
209
+ // Same guard as the footer: the settings list needs pi's TUI.
210
+ if (!ctx.hasUI || ctx.mode !== "tui") return ctx.ui.notify(`pi-hud-plus: /${name} needs pi's interactive UI.`, "error");
211
+ await guidedConfig(ctx, fromScratch);
212
+ },
213
+ });
214
+ }
215
+ }