pi-hud-plus 0.2.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,17 @@
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
+
3
15
  ## [0.2.0] - 2026-11-17
4
16
 
5
17
  ### New Features
package/README.md CHANGED
@@ -35,6 +35,7 @@ The default `lineLayout` is `"expanded"`: one Line per Element, in `elementOrder
35
35
  |---|---|---|
36
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
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` |
38
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` |
39
40
  | `memory` | `Approx RAM ████░░ 12 GB / 16 GB (75%)`: system RAM. Expanded layout only | `display.showMemoryUsage` |
40
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` |
@@ -50,7 +51,7 @@ The **Custom line** (`display.customLine`) is static text that goes at the start
50
51
 
51
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.
52
53
 
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
+ `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.
54
55
 
55
56
  ## Config
56
57
 
@@ -68,7 +69,7 @@ Top level:
68
69
  | `lineLayout` | `"expanded"` | `"expanded"`, `"compact"` |
69
70
  | `showSeparators` | `false` | boolean |
70
71
  | `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
+ | `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 |
72
73
  | `extraCommand` | `""` (off) | shell command, see [Extra command](#extra-command) |
73
74
 
74
75
  `gitStatus`:
@@ -78,7 +79,7 @@ Top level:
78
79
  | `enabled` | `true` | boolean. When off, no git commands run |
79
80
  | `showDirty` | `true` | boolean: `*` after the branch when the tree is dirty |
80
81
  | `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
+ | `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) |
82
83
  | `branchOverflow` | `"truncate"` | `"truncate"` keeps project and git in one segment; `"wrap"` gives git its own segment |
83
84
  | `pushWarningThreshold` | `0` (off) | colour `↑n` with `colors.warning` from this many unpushed commits |
84
85
  | `pushCriticalThreshold` | `0` (off) | colour `↑n` with `colors.critical` from this many unpushed commits |
@@ -102,6 +103,15 @@ Top level:
102
103
  | `contextWarningThreshold` | `70` | 0–100 |
103
104
  | `contextCriticalThreshold` | `85` | 0–100 |
104
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 |
105
115
  | `showPromptCache` | `false` | boolean |
106
116
  | `promptCacheTtlSeconds` | `300` | positive whole number |
107
117
  | `showMemoryUsage` | `false` | boolean |
@@ -115,7 +125,7 @@ Top level:
115
125
  | `timeFormat` | `"relative"` | `"relative"` (`3m ago`), `"absolute"` (`2026-11-14 09:30`), `"both"`; `"elapsed"` and `"elapsedAndAbsolute"` read like `"relative"` and `"both"` |
116
126
  | `showSessionTokens` | `false` | boolean |
117
127
  | `showExtensionStatuses` | `true` | boolean |
118
- | `mergeGroups` | `[]` | arrays of at least two Elements, e.g. `[["context", "promptCache"]]` |
128
+ | `mergeGroups` | `[["context", "usage"]]` | arrays of at least two Elements; `[]` turns merging off |
119
129
  | `customLine` | `""` | static text (max 80 chars) |
120
130
  | `customLinePosition` | `"last"` | `"first"`, `"last"` |
121
131
 
@@ -124,6 +134,8 @@ Top level:
124
134
  | Field | Default | Colours |
125
135
  |---|---|---|
126
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`) |
127
139
  | `warning` | `"yellow"` | context at or above the warning threshold, cache about to expire |
128
140
  | `critical` | `"red"` | context at or above the critical threshold |
129
141
  | `model` | `"cyan"` | model badge |
@@ -173,7 +185,43 @@ Then run `/reload`.
173
185
  { "extraCommand": "echo '{\"label\": \"on-call: alice\"}'" }
174
186
  ```
175
187
 
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.
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.
223
+
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.
177
225
 
178
226
  ## Coexisting with other footer extensions
179
227
 
@@ -185,22 +233,29 @@ If another footer extension (for example pi-powerbar) takes the footer, pi-hud-p
185
233
 
186
234
  To see the HUD, disable the other footer extension with `pi config`, then start a new session or run `/reload`.
187
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
+
188
240
  ## Language
189
241
 
190
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.
191
243
 
192
244
  ## Differences from claude-hud
193
245
 
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.
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.
196
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.
197
253
  - **Renamed fields, no aliases**: `display.showClaudeCodeVersion` is `display.showVersion`, and `display.showEffortLevel` is `display.showThinkingLevel`.
198
254
  - **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`.
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"]]`.
200
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.
201
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
- - **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
259
  - **`max` thinking level**: pi's `max` level, which claude-hud has no equivalent for, shows as `◕` like `xhigh`.
205
260
  - **Chinese relative times**: keep claude-hud's unit style, so `3m前`, not `3分钟前`.
206
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.2.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. */
package/src/commands.ts CHANGED
@@ -13,6 +13,7 @@ const TOGGLES: [key: keyof HudConfig["display"], label: string][] = [
13
13
  ["showProject", "Project"],
14
14
  ["showConfigCounts", "Environment line"],
15
15
  ["showTokenBreakdown", "Token breakdown"],
16
+ ["showUsage", "Usage limits"],
16
17
  ["showSpeed", "Output speed"],
17
18
  ["showDuration", "Session duration"],
18
19
  ["showSessionName", "Session name"],
@@ -73,8 +74,9 @@ function preset(name: string): Values {
73
74
  delete minimal.language;
74
75
  delete minimal.customLine;
75
76
  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;
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" };
78
80
  }
79
81
 
80
82
  /** Only rows that changed are written, so a value the guided rows can't express (e.g. separators in expanded) survives. */
package/src/config.ts CHANGED
@@ -1,9 +1,11 @@
1
1
  import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
+ import { createDebug } from "./debug.ts";
3
4
  import type { Language } from "./i18n/types.ts";
4
5
 
5
6
  export type LineLayoutType = "compact" | "expanded";
6
7
  export type ContextValueMode = "percent" | "tokens" | "remaining" | "both";
8
+ export type UsageValueMode = "percent" | "remaining";
7
9
  export type GitBranchOverflowMode = "truncate" | "wrap";
8
10
 
9
11
  /**
@@ -16,7 +18,7 @@ export type GitBranchOverflowMode = "truncate" | "wrap";
16
18
  export type ModelFormatMode = "full" | "compact" | "short";
17
19
  export type TimeFormatMode = "relative" | "absolute" | "both" | "elapsed" | "elapsedAndAbsolute";
18
20
  export type CustomLinePosition = "first" | "last";
19
- export type HudElement = "project" | "context" | "promptCache" | "memory" | "environment" | "tools" | "sessionTime";
21
+ export type HudElement = "project" | "context" | "usage" | "promptCache" | "memory" | "environment" | "tools" | "sessionTime";
20
22
 
21
23
  export type HudColorName =
22
24
  | "dim"
@@ -33,7 +35,9 @@ export type HudColorValue = HudColorName | number | string;
33
35
 
34
36
  export interface HudColorOverrides {
35
37
  context: HudColorValue;
38
+ usage: HudColorValue;
36
39
  warning: HudColorValue;
40
+ usageWarning: HudColorValue;
37
41
  critical: HudColorValue;
38
42
  model: HudColorValue;
39
43
  project: HudColorValue;
@@ -48,6 +52,7 @@ export interface HudColorOverrides {
48
52
  export const DEFAULT_ELEMENT_ORDER: HudElement[] = [
49
53
  "project",
50
54
  "context",
55
+ "usage",
51
56
  "promptCache",
52
57
  "memory",
53
58
  "environment",
@@ -55,6 +60,8 @@ export const DEFAULT_ELEMENT_ORDER: HudElement[] = [
55
60
  "sessionTime",
56
61
  ];
57
62
 
63
+ export const DEFAULT_MERGE_GROUPS: HudElement[][] = [["context", "usage"]];
64
+
58
65
  const KNOWN_ELEMENTS = new Set<HudElement>(DEFAULT_ELEMENT_ORDER);
59
66
 
60
67
  export interface HudConfig {
@@ -84,6 +91,11 @@ export interface HudConfig {
84
91
  showDuration: boolean;
85
92
  showSpeed: boolean;
86
93
  showTokenBreakdown: boolean;
94
+ showUsage: boolean;
95
+ usageValue: UsageValueMode;
96
+ usageBarEnabled: boolean;
97
+ showResetLabel: boolean;
98
+ usageCompact: boolean;
87
99
  showTools: boolean;
88
100
  toolNameMaxLength: number;
89
101
  toolsMaxVisible: number;
@@ -100,7 +112,13 @@ export interface HudConfig {
100
112
  mergeGroups: HudElement[][];
101
113
  contextWarningThreshold: number;
102
114
  contextCriticalThreshold: number;
115
+ usageThreshold: number;
116
+ /** Shows the Weekly part at or above this % used; it gates the Monthly part too. */
117
+ sevenDayThreshold: number;
103
118
  environmentThreshold: number;
119
+ /** The External usage snapshot file. "" = off. */
120
+ externalUsagePath: string;
121
+ externalUsageFreshnessMs: number;
104
122
  modelFormat: ModelFormatMode;
105
123
  modelOverride: string;
106
124
  customLine: string;
@@ -136,6 +154,11 @@ export const DEFAULT_CONFIG: HudConfig = {
136
154
  showDuration: false,
137
155
  showSpeed: false,
138
156
  showTokenBreakdown: true,
157
+ showUsage: true,
158
+ usageValue: "percent",
159
+ usageBarEnabled: true,
160
+ showResetLabel: true,
161
+ usageCompact: false,
139
162
  showTools: false,
140
163
  toolNameMaxLength: 0,
141
164
  toolsMaxVisible: 4,
@@ -149,10 +172,14 @@ export const DEFAULT_CONFIG: HudConfig = {
149
172
  showSessionStartDate: false,
150
173
  showLastResponseAt: false,
151
174
  showExtensionStatuses: true,
152
- mergeGroups: [],
175
+ mergeGroups: DEFAULT_MERGE_GROUPS.map((group) => [...group]),
153
176
  contextWarningThreshold: 70,
154
177
  contextCriticalThreshold: 85,
178
+ usageThreshold: 0,
179
+ sevenDayThreshold: 80,
155
180
  environmentThreshold: 0,
181
+ externalUsagePath: "",
182
+ externalUsageFreshnessMs: 300000,
156
183
  modelFormat: "full",
157
184
  modelOverride: "",
158
185
  customLine: "",
@@ -161,7 +188,9 @@ export const DEFAULT_CONFIG: HudConfig = {
161
188
  },
162
189
  colors: {
163
190
  context: "green",
191
+ usage: "brightBlue",
164
192
  warning: "yellow",
193
+ usageWarning: "brightMagenta",
165
194
  critical: "red",
166
195
  model: "cyan",
167
196
  project: "yellow",
@@ -217,9 +246,9 @@ function validateElementOrder(value: unknown): HudElement[] {
217
246
  return elementOrder.length > 0 ? elementOrder : [...DEFAULT_ELEMENT_ORDER];
218
247
  }
219
248
 
220
- // claude-hud falls back to its default group when nothing valid survives; our default is [] so every invalid case is [].
221
249
  function validateMergeGroups(value: unknown): HudElement[][] {
222
- if (!Array.isArray(value)) return [];
250
+ if (!Array.isArray(value)) return DEFAULT_MERGE_GROUPS.map((group) => [...group]);
251
+ if (value.length === 0) return [];
223
252
 
224
253
  const usedElements = new Set<HudElement>();
225
254
  const mergeGroups: HudElement[][] = [];
@@ -235,7 +264,7 @@ function validateMergeGroups(value: unknown): HudElement[][] {
235
264
  }
236
265
  }
237
266
 
238
- return mergeGroups;
267
+ return mergeGroups.length > 0 ? mergeGroups : DEFAULT_MERGE_GROUPS.map((group) => [...group]);
239
268
  }
240
269
 
241
270
  function validateThreshold(value: unknown, max = 100): number {
@@ -263,6 +292,11 @@ function validateNonNegativeInteger(value: unknown, fallback: number): number {
263
292
  return value;
264
293
  }
265
294
 
295
+ function validateFreshnessMs(value: unknown): number {
296
+ if (typeof value !== "number" || !Number.isFinite(value)) return DEFAULT_CONFIG.display.externalUsageFreshnessMs;
297
+ return Math.max(0, Math.floor(value));
298
+ }
299
+
266
300
  function truncatedString(value: unknown, fallback: string): string {
267
301
  return typeof value === "string" ? value.slice(0, 80) : fallback;
268
302
  }
@@ -307,6 +341,11 @@ export function mergeConfig(userConfig: unknown): HudConfig {
307
341
  showDuration: displayBool("showDuration"),
308
342
  showSpeed: displayBool("showSpeed"),
309
343
  showTokenBreakdown: displayBool("showTokenBreakdown"),
344
+ showUsage: displayBool("showUsage"),
345
+ usageValue: oneOf(display.usageValue, ["percent", "remaining"] as const, D.display.usageValue),
346
+ usageBarEnabled: displayBool("usageBarEnabled"),
347
+ showResetLabel: displayBool("showResetLabel"),
348
+ usageCompact: displayBool("usageCompact"),
310
349
  showTools: displayBool("showTools"),
311
350
  toolNameMaxLength: validateNonNegativeInteger(display.toolNameMaxLength, D.display.toolNameMaxLength),
312
351
  toolsMaxVisible: validateNonNegativeInteger(display.toolsMaxVisible, D.display.toolsMaxVisible),
@@ -323,7 +362,12 @@ export function mergeConfig(userConfig: unknown): HudConfig {
323
362
  mergeGroups: validateMergeGroups(display.mergeGroups),
324
363
  contextWarningThreshold: validateContextThreshold(display.contextWarningThreshold, D.display.contextWarningThreshold),
325
364
  contextCriticalThreshold: validateContextThreshold(display.contextCriticalThreshold, D.display.contextCriticalThreshold),
365
+ usageThreshold: validateThreshold(display.usageThreshold, 100),
366
+ // claude-hud's validateThreshold turns an absent key into 0 too, against its documented default of 80.
367
+ sevenDayThreshold: display.sevenDayThreshold === undefined ? D.display.sevenDayThreshold : validateThreshold(display.sevenDayThreshold, 100),
326
368
  environmentThreshold: validateThreshold(display.environmentThreshold, 100),
369
+ externalUsagePath: typeof display.externalUsagePath === "string" ? display.externalUsagePath.trim() : "",
370
+ externalUsageFreshnessMs: validateFreshnessMs(display.externalUsageFreshnessMs),
327
371
  modelFormat: oneOf(display.modelFormat, ["full", "compact", "short"] as const, D.display.modelFormat),
328
372
  modelOverride: truncatedString(display.modelOverride, D.display.modelOverride),
329
373
  customLine: truncatedString(display.customLine, D.display.customLine),
@@ -336,7 +380,9 @@ export function mergeConfig(userConfig: unknown): HudConfig {
336
380
  },
337
381
  colors: {
338
382
  context: color("context"),
383
+ usage: color("usage"),
339
384
  warning: color("warning"),
385
+ usageWarning: color("usageWarning"),
340
386
  critical: color("critical"),
341
387
  model: color("model"),
342
388
  project: color("project"),
@@ -360,12 +406,17 @@ export function deepMerge(base: Raw, override: Raw): Raw {
360
406
  return merged;
361
407
  }
362
408
 
409
+ const debug = createDebug("config");
410
+
363
411
  /** Missing, unreadable, unparseable or non-object files count as empty so the HUD still renders. */
364
412
  function readJsonObject(file: string): Raw {
365
413
  try {
366
414
  const parsed: unknown = JSON.parse(fs.readFileSync(file, "utf8"));
367
- return isObject(parsed) ? parsed : {};
368
- } catch {
415
+ if (isObject(parsed)) return parsed;
416
+ debug(`Ignoring ${file}: not a JSON object`);
417
+ return {};
418
+ } catch (error) {
419
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") debug(`Failed to read ${file}:`, error);
369
420
  return {};
370
421
  }
371
422
  }
package/src/debug.ts ADDED
@@ -0,0 +1,21 @@
1
+ // Ported from claude-hud src/debug.ts. pi owns the terminal, so lines go to a file in pi's agent dir instead of stderr.
2
+ import { appendFileSync } from "node:fs";
3
+ import path from "node:path";
4
+ import { format } from "node:util";
5
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
6
+
7
+ /**
8
+ * A namespaced logger, enabled by DEBUG=pi-hud-plus or DEBUG=*.
9
+ * Writes to ~/.pi/agent/pi-hud-plus-debug.log.
10
+ */
11
+ export function createDebug(namespace: string) {
12
+ return function debug(msg: string, ...args: unknown[]): void {
13
+ const env = process.env.DEBUG;
14
+ if (!env?.includes("pi-hud-plus") && env !== "*") return;
15
+ try {
16
+ appendFileSync(path.join(getAgentDir(), "pi-hud-plus-debug.log"), `${new Date().toISOString()} [pi-hud-plus:${namespace}] ${format(msg, ...args)}\n`, { mode: 0o600 });
17
+ } catch {
18
+ // Logging must never break the HUD
19
+ }
20
+ };
21
+ }
@@ -0,0 +1,79 @@
1
+ import * as fs from "node:fs";
2
+ import type { HudConfig } from "./config.ts";
3
+ import { sanitize } from "./sanitize.ts";
4
+ import type { UsageLimit } from "./types.ts";
5
+
6
+ /** Ported from claude-hud's external-usage (read side). The file another tool writes, in claude-hud's format. */
7
+ interface ExternalUsageSnapshot {
8
+ five_hour?: { used_percentage?: unknown; resets_at?: unknown } | null;
9
+ seven_day?: { used_percentage?: unknown; resets_at?: unknown } | null;
10
+ updated_at?: unknown;
11
+ balance_label?: unknown;
12
+ }
13
+
14
+ const MAX_BALANCE_LABEL_LENGTH = 50;
15
+
16
+ /** A UsageLimit with every Limit window null; a fresh object, so callers can fill it in. */
17
+ export const emptyUsageLimit = (): UsageLimit => ({ fiveHour: null, sevenDay: null, monthly: null, fiveHourResetAt: null, sevenDayResetAt: null, monthlyResetAt: null });
18
+
19
+ /** A percent rounded and clamped to 0-100; null unless a finite number. */
20
+ export function parseUsagePercent(value: unknown): number | null {
21
+ if (typeof value !== "number" || !Number.isFinite(value)) return null;
22
+ return Math.round(Math.min(100, Math.max(0, value)));
23
+ }
24
+
25
+ /** claude-hud's balance_label sanitising: escape sequences out, then control and bidi characters, cut to 50. */
26
+ export function sanitizeBalanceLabel(value: unknown): string | null {
27
+ if (typeof value !== "string") return null;
28
+ const sanitized = sanitize(
29
+ value
30
+ .replace(/\x1B\[[0-?]*[ -/]*[@-~]/g, "")
31
+ .replace(/\x1B\][^\x07\x1B]*(?:\x07|\x1B\\)/g, "")
32
+ .replace(/\x1B[@-Z\\-_]/g, ""),
33
+ ).trim();
34
+ if (!sanitized) return null;
35
+ return sanitized.length <= MAX_BALANCE_LABEL_LENGTH ? sanitized : `${sanitized.slice(0, MAX_BALANCE_LABEL_LENGTH - 3)}...`;
36
+ }
37
+
38
+ /** A number above 1e12 is epoch ms, otherwise epoch seconds; strings go through Date. */
39
+ function parseDateValue(value: unknown): Date | null {
40
+ if (typeof value === "number") {
41
+ if (!Number.isFinite(value) || value <= 0) return null;
42
+ const date = new Date(value > 1e12 ? value : value * 1000);
43
+ return Number.isNaN(date.getTime()) ? null : date;
44
+ }
45
+ if (typeof value === "string" && value.trim()) {
46
+ const date = new Date(value);
47
+ return Number.isNaN(date.getTime()) ? null : date;
48
+ }
49
+ return null;
50
+ }
51
+
52
+ /** The External usage snapshot at `display.externalUsagePath`, or null when off, missing, stale or malformed. A small sync read. */
53
+ export function getUsageFromExternalSnapshot(config: HudConfig, now = Date.now()): UsageLimit | null {
54
+ const snapshotPath = config.display.externalUsagePath;
55
+ if (!snapshotPath) return null;
56
+
57
+ try {
58
+ const parsed = JSON.parse(fs.readFileSync(snapshotPath, "utf8")) as ExternalUsageSnapshot;
59
+ const updatedAt = parseDateValue(parsed.updated_at)?.getTime();
60
+ if (updatedAt === undefined || now - updatedAt > config.display.externalUsageFreshnessMs) return null;
61
+
62
+ const fiveHour = parseUsagePercent(parsed.five_hour?.used_percentage);
63
+ const sevenDay = parseUsagePercent(parsed.seven_day?.used_percentage);
64
+ const balanceLabel = sanitizeBalanceLabel(parsed.balance_label);
65
+ if (fiveHour === null && sevenDay === null && balanceLabel === null) return null;
66
+
67
+ const fiveHourResetAt = parseDateValue(parsed.five_hour?.resets_at);
68
+ const sevenDayResetAt = parseDateValue(parsed.seven_day?.resets_at);
69
+ // An unparseable reset rejects the whole snapshot, as in claude-hud.
70
+ if (parsed.five_hour && parsed.five_hour.resets_at != null && fiveHourResetAt === null) return null;
71
+ if (parsed.seven_day && parsed.seven_day.resets_at != null && sevenDayResetAt === null) return null;
72
+
73
+ const usage: UsageLimit = { ...emptyUsageLimit(), fiveHour, sevenDay, fiveHourResetAt, sevenDayResetAt };
74
+ if (balanceLabel !== null) usage.balanceLabel = balanceLabel;
75
+ return usage;
76
+ } catch {
77
+ return null;
78
+ }
79
+ }
package/src/extra-cmd.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  // Ported from claude-hud src/extra-cmd.ts. Changes for pi: the command comes from config (no --extra-cmd
2
- // argv parsing) and runs through pi.exec as `sh -c`, since pi.exec doesn't use a shell. No debug logging.
2
+ // argv parsing) and runs through pi.exec as `sh -c`, since pi.exec doesn't use a shell.
3
+ import { createDebug } from "./debug.ts";
3
4
  import type { Exec } from "./git.ts";
4
5
  import { sanitize as stripControls } from "./sanitize.ts";
5
6
 
@@ -7,6 +8,9 @@ const MAX_BUFFER = 10 * 1024; // 10KB - plenty for a label
7
8
  const MAX_LABEL_LENGTH = 50;
8
9
  const TIMEOUT_MS = 3000;
9
10
 
11
+ // Messages never include the command or its output: either may hold secrets.
12
+ const debug = createDebug("extra-cmd");
13
+
10
14
  /**
11
15
  * Sanitize output to prevent terminal escape injection.
12
16
  * Strips whole ANSI/OSC escape sequences (so their parameters don't show), then control and bidi characters.
@@ -30,8 +34,21 @@ export function sanitize(input: string): string {
30
34
  export async function runExtraCmd(exec: Exec, cmd: string, timeout: number = TIMEOUT_MS): Promise<string | null> {
31
35
  try {
32
36
  const { stdout, code, killed } = await exec("sh", ["-c", cmd], { timeout, maxBuffer: MAX_BUFFER });
33
- if (code !== 0 || killed) return null;
34
- const data: unknown = JSON.parse(stdout.trim());
37
+ if (killed) {
38
+ debug(`Command timed out after ${timeout}ms`);
39
+ return null;
40
+ }
41
+ if (code !== 0) {
42
+ debug(`Command failed with exit code ${code}`);
43
+ return null;
44
+ }
45
+ let data: unknown;
46
+ try {
47
+ data = JSON.parse(stdout.trim());
48
+ } catch {
49
+ debug("Failed to parse JSON output");
50
+ return null;
51
+ }
35
52
  if (typeof data === "object" && data !== null && "label" in data && typeof data.label === "string") {
36
53
  let label = sanitize(data.label);
37
54
  if (label.length > MAX_LABEL_LENGTH) {
@@ -39,8 +56,10 @@ export async function runExtraCmd(exec: Exec, cmd: string, timeout: number = TIM
39
56
  }
40
57
  return label;
41
58
  }
59
+ debug(`Command output missing 'label' field or invalid type`);
42
60
  return null;
43
61
  } catch {
62
+ debug("Command failed to run");
44
63
  return null;
45
64
  }
46
65
  }
package/src/git.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  // Ported from claude-hud src/git.ts. Changes for pi: commands go through pi.exec (which resolves with an
2
2
  // exit code instead of rejecting), every command passes --no-optional-locks, diff and rev-list are gated
3
- // by config, and the branch (rev-parse) and branchUrl (remote get-url) come from elsewhere / are dropped.
3
+ // by config, the branch (rev-parse) comes from pi's footerData, and branchUrl becomes githubUrl (the branch isn't known here).
4
+ import { stat } from "node:fs/promises";
5
+ import path from "node:path";
4
6
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
5
7
 
6
8
  export type Exec = ExtensionAPI["exec"];
@@ -23,6 +25,8 @@ export interface FileStats {
23
25
  deleted: number;
24
26
  untracked: number;
25
27
  trackedFiles: TrackedFile[];
28
+ /** The repo root that trackedFiles' paths are relative to; set when showFileStats collected them. */
29
+ root?: string;
26
30
  }
27
31
 
28
32
  export interface GitStatus {
@@ -32,11 +36,15 @@ export interface GitStatus {
32
36
  behind: number;
33
37
  fileStats?: FileStats;
34
38
  lineDiff?: LineDiff;
39
+ /** The GitHub origin's https URL, for linking the branch. */
40
+ githubUrl?: string;
35
41
  }
36
42
 
37
43
  export interface GitStatusOptions {
38
44
  showAheadBehind: boolean;
39
45
  showFileStats: boolean;
46
+ /** Look up the GitHub origin for the branch link (expanded layout only). */
47
+ linkBranch: boolean;
40
48
  }
41
49
 
42
50
  /** Runs `git --no-optional-locks <args>`, rejecting like execFile on a non-zero exit or timeout. */
@@ -75,6 +83,15 @@ export async function getGitStatus(exec: Exec, cwd: string, options: GitStatusOp
75
83
  } catch {
76
84
  // Ignore errors
77
85
  }
86
+ // claude-hud sorts at render time; here it runs once per git job instead of every frame.
87
+ if (fileStats) {
88
+ try {
89
+ fileStats.root = (await git(exec, cwd, ['rev-parse', '--show-toplevel'], 1000)).trim();
90
+ await sortByMtime(fileStats.trackedFiles, fileStats.root);
91
+ } catch {
92
+ // Keep git's order
93
+ }
94
+ }
78
95
  }
79
96
 
80
97
  // Get ahead/behind counts
@@ -93,7 +110,19 @@ export async function getGitStatus(exec: Exec, cwd: string, options: GitStatusOp
93
110
  }
94
111
  }
95
112
 
96
- return { isDirty, ahead, behind, fileStats, lineDiff };
113
+ let githubUrl: string | undefined;
114
+ if (options.linkBranch) try {
115
+ const httpsBase = (await git(exec, cwd, ['remote', 'get-url', 'origin'], 1000))
116
+ .trim()
117
+ .replace(/^git@github\.com:/, 'https://github.com/')
118
+ .replace(/^ssh:\/\/git@github\.com\//, 'https://github.com/')
119
+ .replace(/\.git$/, '');
120
+ if (httpsBase.startsWith('https://github.com/')) githubUrl = httpsBase;
121
+ } catch {
122
+ // No remote or not GitHub
123
+ }
124
+
125
+ return { isDirty, ahead, behind, fileStats, lineDiff, githubUrl };
97
126
  }
98
127
 
99
128
  /**
@@ -203,6 +232,13 @@ function parseNumstat(numstatOutput: string, trackedPaths: Set<string>): { total
203
232
  return { totalDiff, perFileDiff };
204
233
  }
205
234
 
235
+ /** Newest-modified first; files that can't be stat'd (deleted) go last. */
236
+ async function sortByMtime(files: TrackedFile[], root: string): Promise<void> {
237
+ const mtimes = new Map(await Promise.all(files.map(async (file) =>
238
+ [file, await stat(path.resolve(root, file.fullPath)).then((s) => s.mtimeMs, () => 0)] as const)));
239
+ files.sort((a, b) => mtimes.get(b)! - mtimes.get(a)!);
240
+ }
241
+
206
242
  function applyLineDiffsToFiles(files: TrackedFile[], perFileDiff: Map<string, LineDiff>): void {
207
243
  for (const file of files) {
208
244
  const diff = perFileDiff.get(file.fullPath);