@erichll/pi-statusline 0.5.0 → 0.6.1

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,72 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.6.1 - 2026-10-16
4
+
5
+ ### Changed
6
+
7
+ - Mute the runtime row so it no longer competes with the editor: the duration,
8
+ run metrics, session age and tokens use Pi's muted color, and the running
9
+ (`●`) and done (`✓`) symbols are muted too. Only problems stay colored: a
10
+ failed run (`✗`), `awaiting input`, `no content`, `compacting…`, compaction
11
+ failures and cache below 50%. Cache is no longer green from 80%. Explicit
12
+ `session`/`tokens` segment colors still apply.
13
+ - Show run counts label first, like `avg` and `cache`: `turns 4` and
14
+ `compactions 1` instead of `4 turns` and `1 compaction`.
15
+
16
+ ## 0.6.0 - 2026-10-16
17
+
18
+ ### Added
19
+
20
+ - Add a tool activity row between the main line and the runtime row, shown
21
+ once the current run has used tools: `◐ bash npm test 12s · ✓ read ×5 ·
22
+ ✗ bash ×1 · +2`. Up to two running tools show their target (shell command
23
+ without `cd`/env prefixes, file name, search pattern or directory) and timer;
24
+ same-name calls merge as `×N`. Completed (`✓`) and failed (`✗`) calls are
25
+ counted per run and kept in the last-run summary.
26
+ - Count nested calls (`parentToolCallId`) but represent them by their parent
27
+ while running. Calls ended by a user cancellation are not counted as failures.
28
+ - Add a `session` segment on the runtime row, enabled by default: the time
29
+ since the session was created (`󰥔 2h 6m`; `◷` in Unicode and `ses:` in ASCII
30
+ icon modes), to the minute and before session tokens. It is read once per
31
+ session from Pi's session header, survives reloads and resuming, restarts with
32
+ `/new` or a fork, and is hidden when the header time is missing or invalid.
33
+ Existing segment lists gain it before `tokens` unless they list it explicitly.
34
+ - Add `runtime.toolsMaxVisible` (1–8, default 4) for completed tool kinds shown
35
+ before `+N`, editable in the panel. Narrow rows fold kinds, then drop targets,
36
+ then timers.
37
+ - Label quota windows from the reported length (`x-codex-*-window-minutes`
38
+ headers and WebSocket `window_minutes`): `5h`, `1d`, `7d` or `30d` within 5%,
39
+ otherwise exact (`1h30m`). Without a reported length a window stays unlabeled
40
+ rather than guessed; a malformed length drops only the label.
41
+ - Add tool target, tool counting, window label, per-window color and session age
42
+ tests, and extend the offline PTY smoke with the tool row, completed counts
43
+ and session age.
44
+
45
+ ### Changed
46
+
47
+ - Render quota as `5h ███░░░░░░░ 27% 4h8m · 7d ████░░░░░░ 44% 6d1h`: dim labels
48
+ and `·` separators, muted countdowns without brackets, and each window colored
49
+ by its own usage (accent, warning above 70%, error above 90%). An explicit
50
+ segment `color` still applies to both. Unlabeled windows keep their countdown
51
+ instead of their bar on narrow terminals.
52
+ - Restyle the runtime row and move it to the bottom of the footer. A run status
53
+ symbol (`●` running, `✓` done, `✗` failed, `⊘` cancelled) precedes the
54
+ duration in place of `Elapsed`; labels are dim and lowercase
55
+ (`avg 39 tok/s · cache 100% · 11 turns · 1 compaction`); cache is green from
56
+ 80% and warning below 50%. ASCII mode uses `*`, `ok`, `x` and `-`.
57
+ - Keep average speed and cache visible while tools run or input is awaited.
58
+ `awaiting input`, `no content` and `compacting…` follow the duration in the
59
+ warning color; `no content` was previously muted.
60
+ - Move the session token total (`tokens`) from the main line to the runtime row,
61
+ before other extensions' statuses. It keeps its icon, color and enablement.
62
+ - `runtime.tools` now controls the tool row. Existing configurations with
63
+ `"tools": true` show it after upgrading; set it to `false` to hide it.
64
+
65
+ ### Removed
66
+
67
+ - Remove `Tool X 3s` / `Tools N active` from the runtime row; the tool row
68
+ replaces them.
69
+
3
70
  ## 0.5.0 - 2026-10-14
4
71
 
5
72
  ### Added
package/README.md CHANGED
@@ -4,10 +4,15 @@ A configurable native Pi footer with Git status, session usage, runtime/tool
4
4
  activity and live configuration preview. Leaves the editor intact.
5
5
 
6
6
  ```text
7
-  Example model(high)  󰆼 █░░░░░░░░░ 11.9%  󰉋 pi-packages   main ● *2 ↑2  󰊄 49.4k
8
- Elapsed 5m 42s · Avg 45 tok/s · Cache 86% · Turns 3 · Compactions 1
7
+  Example model(high)  󰆼 █░░░░░░░░░ 11.9%  󰉋 pi-packages   main ● *2 ↑2
8
+ ◐ bash npm test 12s · ✓ read ×5 · ✓ edit ×2
9
+ ● 5m 42s · avg 45 tok/s · cache 86% · turns 3 · compactions 1 · 󰥔 2h 6m · 󰊄 49.4k
9
10
  ```
10
11
 
12
+ Rows, top to bottom: the main segments, tool activity for the current run
13
+ (only once it has used tools), then run status, run metrics, session age and
14
+ tokens, and other extensions' statuses.
15
+
11
16
  ## Install
12
17
 
13
18
  ```sh
@@ -76,16 +81,17 @@ Available segments:
76
81
  | `quota` | Subscription Usage and reset countdowns; hidden without data | On |
77
82
  | `directory` | Current directory | On |
78
83
  | `git` | Branch, dirty/conflict state, staged/unstaged/untracked counts, ahead/behind | On |
79
- | `tokens` | Cumulative session tokens | On |
84
+ | `session` | Time since the session was created, on the bottom row | On |
85
+ | `tokens` | Cumulative session tokens, on the bottom row | On |
80
86
  | `cost` | Pi-recorded cumulative USD cost | Off |
81
87
  | `input`, `output`, `cacheRead`, `cacheWrite` | Individual session token counters | Off |
82
- | `statuses` | Other extensions' text on the second row | On |
88
+ | `statuses` | Other extensions' text, at the end of the bottom row | On |
83
89
 
84
90
  `segments` is an ordered array of
85
91
  `{ id, enabled, icon?, color?, iconColor?, background? }`. Omitted segments are
86
- disabled, **except `quota`**: old configurations automatically gain it after
87
- `context` (or at the end if context is absent). To keep it off, include
88
- `{ "id": "quota", "enabled": false }`.
92
+ disabled, **except `quota` and `session`**: old configurations automatically
93
+ gain `quota` after `context` and `session` before `tokens` (or at the end when
94
+ the anchor is absent). To keep one off, include it with `"enabled": false`.
89
95
 
90
96
  Colors accept `#RRGGBB` or supported Pi theme tokens such as `accent`, `muted`,
91
97
  `success`, `warning` and `error`; explicit colors override automatic thresholds.
@@ -100,20 +106,23 @@ Removing the file restores defaults on reload; panel saves are atomic.
100
106
  Codex quota appears after context when valid data is available:
101
107
 
102
108
  ```text
103
- 󰆼 █░░░░░░░░░ 4.6%  󰦖 ████░░░░░░ 40%[3h3m] | ██░░░░░░░░ 21%[4d9h]
109
+ 󰆼 █░░░░░░░░░ 4.6%  󰦖 5h ████░░░░░░ 40% 3h3m · 7d ██░░░░░░░░ 21% 4d9h
104
110
  ```
105
111
 
106
- Bars show **used** percentages for the primary and secondary windows (usually
107
- 5 hours and 7 days), with live reset countdowns. The default color is Pi's
108
- accent, changing to warning above 70% and error above 90%. Narrow terminals
109
- omit countdowns, then bars, then the segment rather than truncate a window.
112
+ Bars show **used** percentages for the primary and secondary windows, with live
113
+ reset countdowns. Labels come from the reported window length (`5h`, `1d`,
114
+ `7d`, `30d` within 5%, otherwise exact such as `1h30m`); without one, the
115
+ window is unlabeled rather than guessed. Each window is colored on its own:
116
+ Pi's accent, warning above 70% and error above 90%; a segment `color` overrides
117
+ both. Narrow terminals omit countdowns, then bars, then the segment rather than
118
+ truncate a window; an unlabeled window keeps its countdown instead of its bar.
110
119
 
111
120
  Data is observed passively through Pi's provider events:
112
121
 
113
- - **SSE:** `x-codex-{primary,secondary}-{used-percent,reset-at}` response headers.
122
+ - **SSE:** `x-codex-{primary,secondary}-{used-percent,reset-at,window-minutes}` response headers.
114
123
  CLIProxyAPI needs `requests.passthrough-headers: true`.
115
- - **WebSocket:** native `codex.rate_limits` events with numeric `used_percent`
116
- and `reset_at` in `rate_limits.primary` / `secondary`. Other named metered
124
+ - **WebSocket:** native `codex.rate_limits` events with numeric `used_percent`,
125
+ `reset_at` and optional `window_minutes` in `rate_limits.primary` / `secondary`. Other named metered
117
126
  buckets are ignored. The proxy must forward these events.
118
127
 
119
128
  For CLIProxyAPI v8.0.28, each eligible Codex credential needs `websockets: true`
@@ -132,21 +141,36 @@ or RPM/TPM rate limit.
132
141
  - Context is Pi's current estimate, not cumulative consumption; unknown values
133
142
  show `?`. Session totals include recorded usage across the whole session file,
134
143
  including compaction and abandoned branches. Cost is Pi-reported, not an invoice.
135
- - `Elapsed` spans retries, tools, UI waits and compaction. `Avg` is assistant
136
- output tokens / total run seconds, **not inference speed**;
137
- `Cache` is cache-read / (input + cache-read + cache-write). `Turns` counts Pi
138
- turns, not upstream requests; `Compactions` counts successful session entries.
139
- - Tool activity and `Awaiting input` appear while active. `No content 10s`
140
- means no non-empty text, reasoning or tool-call delta was observed; it is not
141
- a server timeout and is suppressed during tools, UI waits and compaction.
144
+ - The bottom row starts with the run status (`●` running, `✓` done, `✗` failed,
145
+ `⊘` cancelled) and its duration, which spans retries, tools, UI waits and
146
+ compaction. `avg` is assistant output tokens / total run seconds, **not
147
+ inference speed**; `cache` is cache-read / (input + cache-read + cache-write).
148
+ `turns` counts Pi turns, not upstream requests; `compactions` counts
149
+ successful session entries. The row stays muted; only a failed run, waits,
150
+ compaction problems and cache below 50% are colored.
151
+ - The run duration (to the second) covers one run, from your message until the
152
+ agent settles, across all its turns. The session age (`󰥔 2h 6m`, to the
153
+ minute) counts from the session header's creation time: it survives reloads
154
+ and resuming, restarts with `/new` or a fork, and is hidden when the header
155
+ time is missing or invalid.
156
+ - `awaiting input` and `no content 10s` follow the duration while active. No
157
+ content means no non-empty text, reasoning or tool-call delta was observed; it
158
+ is not a server timeout and is suppressed during tools, UI waits and compaction.
159
+ - The tool row shows up to two running tools with what they work on (a shell
160
+ command without `cd`/env prefixes, a file name or a search pattern), merging
161
+ same-name calls as `×N`, then this run's completed (`✓`) and failed (`✗`)
162
+ counts. `toolsMaxVisible` (1–8, default 4) completed kinds show before `+N`.
163
+ Nested calls count but are represented by their parent while running; calls
164
+ ended by a cancellation are not failures. Narrow rows fold kinds, then drop
165
+ targets, then timers.
142
166
 
143
167
  All runtime options default to enabled; `noContentSeconds` accepts 1–3600
144
- (default 10). `retainSummary` keeps the last run until the next one;
168
+ (default 10). `tools: false` hides the tool row. `retainSummary` keeps the last run until the next one;
145
169
  `runtime.enabled: false` hides local runtime metrics. Reload/new session resets
146
170
  in-memory runtime summaries, not persisted session totals.
147
171
 
148
172
  Extension statuses remain display-only; a plain `tps` status of `Elapsed …`
149
- replaces the local Elapsed label. Git updates asynchronously; no repository
173
+ supplies the duration. Git updates asynchronously; no repository
150
174
  hides the segment, and query failures show `?`. Narrow layouts prioritize model
151
175
  and context. RPC, JSON and print mode do not install the footer or start polling.
152
176
 
@@ -45,6 +45,10 @@
45
45
  "id": "output",
46
46
  "enabled": false
47
47
  },
48
+ {
49
+ "id": "session",
50
+ "enabled": true
51
+ },
48
52
  {
49
53
  "id": "tokens",
50
54
  "enabled": true
@@ -71,6 +75,7 @@
71
75
  "avg": true,
72
76
  "cache": true,
73
77
  "counts": true,
74
- "retainSummary": true
78
+ "retainSummary": true,
79
+ "toolsMaxVisible": 4
75
80
  }
76
81
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@erichll/pi-statusline",
3
- "version": "0.5.0",
3
+ "version": "0.6.1",
4
4
  "description": "Configurable Pi statusline with live preview, Git and session usage",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/src/config.ts CHANGED
@@ -10,12 +10,12 @@ export function validColor(value: unknown): value is ColorValue {
10
10
  return typeof value === "string" && (/^#[\da-f]{6}$/i.test(value) || (COLORS as readonly string[]).includes(value));
11
11
  }
12
12
  export function presetConfig(): StatuslineConfig {
13
- const enabled = new Set<string>(["model", "thinking", "directory", "git", "context", "quota", "tokens", "statuses"]);
13
+ const enabled = new Set<string>(["model", "thinking", "directory", "git", "context", "quota", "session", "tokens", "statuses"]);
14
14
  return {
15
15
  version: 1, enabled: true, preset: "powerline", icons: "nerd",
16
16
  separator: "powerline", pathMode: "basename", modelDisplay: "name", contextDisplay: "bar", spacing: 1,
17
17
  segments: SEGMENT_IDS.map((id) => ({ id, enabled: enabled.has(id) })),
18
- runtime: { enabled: true, status: true, tools: true, noContent: true, noContentSeconds: 10, avg: true, cache: true, counts: true, retainSummary: true },
18
+ runtime: { enabled: true, status: true, tools: true, noContent: true, noContentSeconds: 10, avg: true, cache: true, counts: true, retainSummary: true, toolsMaxVisible: 4 },
19
19
  };
20
20
  }
21
21
  function record(value: unknown): value is Record<string, unknown> {
@@ -54,7 +54,8 @@ export function parseConfig(raw: unknown): StatuslineConfig {
54
54
  if (key === "noContentSeconds") {
55
55
  if (typeof value !== "number" || !Number.isInteger(value) || value < 1 || value > 3600) throw new Error("Invalid runtime.noContentSeconds (1–3600)");
56
56
  config.runtime.noContentSeconds = value;
57
- } else (config[group] as unknown as Record<string, unknown>)[key] = boolean(value, `${group}.${key}`);
57
+ } else if (key === "toolsMaxVisible") config.runtime.toolsMaxVisible = integer(value, 1, 8, "runtime.toolsMaxVisible");
58
+ else (config[group] as unknown as Record<string, unknown>)[key] = boolean(value, `${group}.${key}`);
58
59
  }
59
60
  }
60
61
  if (raw.segments !== undefined) {
@@ -78,12 +79,15 @@ export function parseConfig(raw: unknown): StatuslineConfig {
78
79
  }
79
80
  return result;
80
81
  });
81
- // Upgrade pre-quota lists once; an explicit quota entry (including disabled) wins.
82
- if (!seen.has("quota")) {
83
- const contextIndex = config.segments.findIndex((segment) => segment.id === "context");
84
- config.segments.splice(contextIndex < 0 ? config.segments.length : contextIndex + 1, 0, { id: "quota", enabled: true });
85
- seen.add("quota");
86
- }
82
+ // Upgrade older lists once with segments added later; an explicit entry (including disabled) wins.
83
+ const insert = (id: "quota" | "session", index: number) => {
84
+ if (seen.has(id)) return;
85
+ config.segments.splice(index < 0 ? config.segments.length : index, 0, { id, enabled: true });
86
+ seen.add(id);
87
+ };
88
+ const contextIndex = config.segments.findIndex((segment) => segment.id === "context");
89
+ insert("quota", contextIndex < 0 ? -1 : contextIndex + 1);
90
+ insert("session", config.segments.findIndex((segment) => segment.id === "tokens"));
87
91
  // All other omissions remain editable but disabled.
88
92
  for (const id of SEGMENT_IDS) if (!seen.has(id)) config.segments.push({ id, enabled: false });
89
93
  }
package/src/index.ts CHANGED
@@ -37,7 +37,7 @@ export default function statusline(pi: ExtensionAPI): void {
37
37
  pi.on("agent_settled", (_event, ctx) => { session?.setContext(ctx); session?.settle(); session?.schedule(true); });
38
38
  pi.on("ui_prompt_start", () => { session?.runtime.uiStart(); session?.schedule(true); });
39
39
  pi.on("ui_prompt_end", () => { session?.runtime.uiEnd(); session?.schedule(true); });
40
- pi.on("tool_execution_start", (event, ctx) => { session?.setContext(ctx); session?.runtime.toolStart(event.toolCallId, event.toolName); session?.schedule(true); });
40
+ pi.on("tool_execution_start", (event, ctx) => { session?.setContext(ctx); session?.runtime.toolStart(event.toolCallId, event.toolName, event.args, event.parentToolCallId); session?.schedule(true); });
41
41
  pi.on("session_before_compact", (_event, ctx) => {
42
42
  session?.setContext(ctx); session?.compaction.start(); session?.runtime.compaction(true); session?.schedule(true);
43
43
  });
@@ -69,7 +69,7 @@ export default function statusline(pi: ExtensionAPI): void {
69
69
  session?.compaction.finish(event.aborted ? "cancelled" : "failed", undefined, event.errorMessage); session?.runtime.compaction(false); refresh(event, ctx);
70
70
  });
71
71
  pi.on("session_tree", resetLive);
72
- pi.on("tool_execution_end", (event, ctx) => { session?.setContext(ctx); session?.runtime.toolEnd(event.toolCallId); session?.requestGit(); session?.schedule(true); });
72
+ pi.on("tool_execution_end", (event, ctx) => { session?.setContext(ctx); session?.runtime.toolEnd(event.toolCallId, event.isError); session?.requestGit(); session?.schedule(true); });
73
73
  pi.on("user_bash", (_event, ctx) => { session?.setContext(ctx); session?.requestGit(); });
74
74
 
75
75
  pi.registerCommand("statusline", {
package/src/panel.ts CHANGED
@@ -41,7 +41,7 @@ export class StatuslinePanel implements Component, Focusable {
41
41
  }
42
42
  private items(): SelectItem[] {
43
43
  if (this.section) {
44
- const labels: Record<string, string> = { enabled: "Runtime metrics", status: "Elapsed / compaction status", tools: "Tool activity", noContent: "No content warning", noContentSeconds: "No content threshold (seconds)", avg: "Average output speed", cache: "Cache read ratio", counts: "Turns and compactions", retainSummary: "Retain last run summary" };
44
+ const labels: Record<string, string> = { enabled: "Runtime metrics", status: "Run status, elapsed and compaction status", tools: "Tool activity row", noContent: "No content warning", noContentSeconds: "No content threshold (seconds)", avg: "Average output speed", cache: "Cache read ratio", counts: "Turns and compactions", retainSummary: "Retain last run summary", toolsMaxVisible: "Completed tool kinds shown" };
45
45
  return [...Object.entries(this.draft[this.section]).map(([key, value]) => ({ value: `option:${key}`, label: `${labels[key] ?? key}: ${value}` })), { value: "back", label: "Back to settings" }];
46
46
  }
47
47
  if (this.editing) {
@@ -64,7 +64,7 @@ export class StatuslinePanel implements Component, Focusable {
64
64
  { value: "modelDisplay", label: `Model display: ${this.draft.modelDisplay}`, description: "name: display name · last: final model ID component" },
65
65
  { value: "contextDisplay", label: `Context display: ${this.draft.contextDisplay}`, description: "text: tokens/capacity(percent) · bar: progress and percent" },
66
66
  { value: "spacing", label: `Spacing above statusline: ${this.draft.spacing}`, description: "Blank lines between the input box and the statusline (0–3)" },
67
- ...this.draft.segments.filter((segment) => segment.id !== "thinking").map((segment) => ({ value: `segment:${segment.id}`, label: `[${segment.enabled ? "x" : " "}] ${segment.id}`, description: segment.id === "statuses" ? "Secondary row · Space toggles, Enter edits" : segment.id === "quota" ? "Subscription Usage · passive headers/events; hidden without data" : "Space toggles · Alt+Up/Down reorders · Enter edits" })),
67
+ ...this.draft.segments.filter((segment) => segment.id !== "thinking").map((segment) => ({ value: `segment:${segment.id}`, label: `[${segment.enabled ? "x" : " "}] ${segment.id}`, description: segment.id === "statuses" || segment.id === "session" || segment.id === "tokens" ? "Runtime row · Space toggles, Enter edits" : segment.id === "quota" ? "Subscription Usage · passive headers/events; hidden without data" : "Space toggles · Alt+Up/Down reorders · Enter edits" })),
68
68
  { value: "runtime", label: "Runtime options" },
69
69
  { value: "save", label: "Save and apply globally" },
70
70
  { value: "reset", label: "Restore defaults in preview" },
@@ -93,12 +93,12 @@ export class StatuslinePanel implements Component, Focusable {
93
93
  if (this.section) {
94
94
  if (value === "back") { this.cancel(); return; }
95
95
  const key = value.slice("option:".length);
96
- if (key === "noContentSeconds") {
97
- this.input = new Input(); this.input.focused = this.hasFocus; this.input.setValue(String(this.draft.runtime.noContentSeconds));
98
- this.inputLabel = "No content threshold (1–3600 seconds)";
96
+ if (key === "noContentSeconds" || key === "toolsMaxVisible") {
97
+ this.input = new Input(); this.input.focused = this.hasFocus; this.input.setValue(String(this.draft.runtime[key]));
98
+ this.inputLabel = key === "noContentSeconds" ? "No content threshold (1–3600 seconds)" : "Completed tool kinds shown before +N (1–8)";
99
99
  this.input.onEscape = () => this.cancel();
100
100
  this.input.onSubmit = (text) => {
101
- try { this.draft = parseConfig({ ...this.draft, runtime: { ...this.draft.runtime, noContentSeconds: Number(text) } }); this.input = undefined; this.error = ""; this.rebuild(value); }
101
+ try { this.draft = parseConfig({ ...this.draft, runtime: { ...this.draft.runtime, [key]: Number(text) } }); this.input = undefined; this.error = ""; this.rebuild(value); }
102
102
  catch (error) { this.error = error instanceof Error ? error.message : String(error); }
103
103
  };
104
104
  } else {
package/src/quota.ts CHANGED
@@ -3,6 +3,8 @@ interface QuotaModel { provider: string; id: string; api: string; baseUrl: strin
3
3
  export interface QuotaWindow {
4
4
  usedPercent: number;
5
5
  resetAtSeconds: number;
6
+ /** Window length reported upstream; optional, and never guessed. */
7
+ windowMinutes?: number;
6
8
  }
7
9
  export interface SubscriptionQuota {
8
10
  primary?: QuotaWindow;
@@ -19,10 +21,12 @@ function headerNumber(value: unknown): number | undefined {
19
21
  return Number.isFinite(number) && number >= 0 ? number : undefined;
20
22
  }
21
23
 
22
- function validatedWindow(usedPercent: unknown, resetAtSeconds: unknown): QuotaWindow | undefined {
24
+ function validatedWindow(usedPercent: unknown, resetAtSeconds: unknown, windowMinutes?: unknown): QuotaWindow | undefined {
23
25
  if (typeof usedPercent !== "number" || !Number.isFinite(usedPercent) || usedPercent < 0 || usedPercent > 100) return undefined;
24
26
  if (typeof resetAtSeconds !== "number" || !Number.isFinite(resetAtSeconds) || resetAtSeconds <= 0 || resetAtSeconds > 8.64e12) return undefined;
25
- return { usedPercent, resetAtSeconds };
27
+ // A bad length only loses the label; the usage itself is still valid.
28
+ const minutes = typeof windowMinutes === "number" && Number.isFinite(windowMinutes) && windowMinutes > 0 && windowMinutes <= 5256000 ? windowMinutes : undefined;
29
+ return { usedPercent, resetAtSeconds, ...(minutes ? { windowMinutes: minutes } : {}) };
26
30
  }
27
31
  function record(value: unknown): value is Record<string, unknown> {
28
32
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -41,18 +45,18 @@ export function readQuotaEvent(data: unknown): SubscriptionQuota | undefined {
41
45
  for (const key of ["primary", "secondary"] as const) {
42
46
  const value = data.rate_limits[key];
43
47
  if (!record(value)) continue;
44
- const window = validatedWindow(value.used_percent, value.reset_at);
48
+ const window = validatedWindow(value.used_percent, value.reset_at, value.window_minutes);
45
49
  if (window) quota[key] = window;
46
50
  }
47
51
  return quota.primary || quota.secondary ? quota : undefined;
48
52
  }
49
53
 
50
- /** Read only Codex usage/reset headers, never credentials or full responses. */
54
+ /** Read only Codex usage/reset/window headers, never credentials or full responses. */
51
55
  export function readQuotaHeaders(headers: Record<string, string>): SubscriptionQuota | undefined {
52
56
  const fields = new Map<string, string>();
53
57
  for (const name of Object.keys(headers)) {
54
58
  const lower = name.toLowerCase();
55
- if (/^x-codex-(primary|secondary)-(used-percent|reset-at)$/.test(lower)) fields.set(lower, headers[name]!);
59
+ if (/^x-codex-(primary|secondary)-(used-percent|reset-at|window-minutes)$/.test(lower)) fields.set(lower, headers[name]!);
56
60
  }
57
61
  const quota: SubscriptionQuota = {};
58
62
  for (const window of ["primary", "secondary"] as const) {
@@ -60,7 +64,7 @@ export function readQuotaHeaders(headers: Record<string, string>): SubscriptionQ
60
64
  const usedPercent = headerNumber(fields.get(`${prefix}used-percent`));
61
65
  const resetAtSeconds = headerNumber(fields.get(`${prefix}reset-at`));
62
66
  // A percentage without a valid reset time cannot yield a trustworthy countdown.
63
- const value = validatedWindow(usedPercent, resetAtSeconds);
67
+ const value = validatedWindow(usedPercent, resetAtSeconds, headerNumber(fields.get(`${prefix}window-minutes`)));
64
68
  if (value) quota[window] = value;
65
69
  }
66
70
  return quota.primary || quota.secondary ? quota : undefined;
@@ -141,15 +145,42 @@ export function formatReset(minutes: number): string {
141
145
  return `${minutes}m`;
142
146
  }
143
147
 
144
- export function renderQuota(quota: QuotaSnapshot | undefined, ascii: boolean, detail: "full" | "bars" | "percent" = "full"): string | undefined {
145
- if (!quota) return undefined;
146
- const windows = [quota.primary, quota.secondary].filter((window) => window !== undefined);
148
+ const STANDARD_WINDOWS = [[300, "5h"], [1440, "1d"], [10080, "7d"], [43200, "30d"]] as const;
149
+ /** `300` → `5h`, `10080` → `7d`; other lengths print exactly (`90` → `1h30m`). */
150
+ export function windowLabel(minutes: number | undefined): string | undefined {
151
+ if (!minutes) return undefined;
152
+ // Codex itself treats lengths within 5% of a standard window as that window.
153
+ for (const [expected, label] of STANDARD_WINDOWS) if (minutes >= expected * 0.95 && minutes <= expected * 1.05) return label;
154
+ const total = Math.max(1, Math.round(minutes));
155
+ const parts = [[Math.floor(total / 1440), "d"], [Math.floor(total % 1440 / 60), "h"], [total % 60, "m"]] as const;
156
+ return parts.filter(([value]) => value > 0).map(([value, unit]) => `${value}${unit}`).join("");
157
+ }
158
+
159
+ export type QuotaDetail = "full" | "bars" | "percent";
160
+ export interface QuotaPiece { usedPercent: number; label?: string; bar?: string; percent: string; reset?: string }
161
+
162
+ /**
163
+ * Windows in display order. Narrower details drop the countdown, then the bar; an
164
+ * unlabeled window keeps its countdown instead, since that is all that tells it apart.
165
+ */
166
+ export function quotaPieces(quota: QuotaSnapshot | undefined, ascii: boolean, detail: QuotaDetail = "full"): QuotaPiece[] | undefined {
167
+ const windows = quota ? [quota.primary, quota.secondary].filter((window) => window !== undefined) : [];
147
168
  if (!windows.length) return undefined;
148
169
  return windows.map((window) => {
149
- const percent = `${Number(window.usedPercent.toFixed(1))}%`;
150
- if (detail === "percent") return percent;
170
+ const label = windowLabel(window.windowMinutes);
151
171
  const full = window.usedPercent > 0 ? Math.max(1, Math.round(window.usedPercent / 10)) : 0;
152
172
  const bar = (ascii ? "#" : "█").repeat(full) + (ascii ? "-" : "░").repeat(10 - full);
153
- return `${bar} ${percent}${detail === "full" ? `[${formatReset(window.resetInMinutes)}]` : ""}`;
154
- }).join(" | ");
173
+ const reset = formatReset(window.resetInMinutes);
174
+ return {
175
+ usedPercent: window.usedPercent, percent: `${Number(window.usedPercent.toFixed(1))}%`,
176
+ ...(label ? { label } : {}),
177
+ ...(detail === "full" || detail === "bars" && label ? { bar } : {}),
178
+ ...(detail === "full" || !label ? { reset } : {}),
179
+ };
180
+ });
181
+ }
182
+ export function quotaSeparator(ascii: boolean): string { return ascii ? " / " : " · "; }
183
+
184
+ export function renderQuota(quota: QuotaSnapshot | undefined, ascii: boolean, detail: QuotaDetail = "full"): string | undefined {
185
+ return quotaPieces(quota, ascii, detail)?.map((piece) => [piece.label, piece.bar, piece.percent, piece.reset].filter(Boolean).join(" ")).join(quotaSeparator(ascii));
155
186
  }
package/src/render.ts CHANGED
@@ -6,23 +6,30 @@ export { cleanText } from "./text.ts";
6
6
  import type { ColorValue, SegmentConfig, SegmentId, StatuslineConfig, StatuslineSnapshot } from "./types.ts";
7
7
  import { emptyGit } from "./git.ts";
8
8
  import { emptyUsage } from "./usage.ts";
9
- import { renderRuntime } from "./runtime-render.ts";
10
- import { renderQuota } from "./quota.ts";
9
+ import { renderRuntime, renderTools } from "./runtime-render.ts";
10
+ import { quotaPieces, quotaSeparator, renderQuota, type QuotaDetail } from "./quota.ts";
11
11
 
12
12
  export type RenderTheme = Pick<Theme, "style" | "colors" | "appearance">;
13
13
  // Keep rainbow hues independent of semantic theme colors, which can repeat.
14
14
  const THINKING_RAINBOW = ["#c084fc", "#f472b6", "#fb923c", "#facc15", "#4ade80", "#22d3ee", "#60a5fa"].map((value) => parseColor(value));
15
15
  const ICONS: Record<StatuslineConfig["icons"], Partial<Record<SegmentId, string>>> = {
16
- unicode: { model: "", directory: "▸", git: "⑂", context: "◉", cost: "$", input: "↑", output: "↓", tokens: "Σ", cacheRead: "R", cacheWrite: "W" },
17
- nerd: { model: "", directory: "󰉋", git: "", context: "󰆼", quota: "󰦖", cost: "$", input: "↑", output: "↓", tokens: "󰊄", cacheRead: "R", cacheWrite: "W" },
18
- ascii: { model: "", directory: "", git: "git:", context: "ctx:", cost: "$", input: "in:", output: "out:", tokens: "tok:", cacheRead: "R:", cacheWrite: "W:" },
16
+ unicode: { model: "", directory: "▸", git: "⑂", context: "◉", cost: "$", input: "↑", output: "↓", session: "◷", tokens: "Σ", cacheRead: "R", cacheWrite: "W" },
17
+ nerd: { model: "", directory: "󰉋", git: "", context: "󰆼", quota: "󰦖", cost: "$", input: "↑", output: "↓", session: "󰥔", tokens: "󰊄", cacheRead: "R", cacheWrite: "W" },
18
+ ascii: { model: "", directory: "", git: "git:", context: "ctx:", cost: "$", input: "in:", output: "out:", session: "ses:", tokens: "tok:", cacheRead: "R:", cacheWrite: "W:" },
19
19
  };
20
- const DROP_ORDER: SegmentId[] = ["cost", "cacheWrite", "cacheRead", "tokens", "output", "input", "thinking", "git", "directory"];
20
+ const DROP_ORDER: SegmentId[] = ["cost", "cacheWrite", "cacheRead", "output", "input", "thinking", "git", "directory"];
21
21
  export function formatTokens(value: number): string {
22
22
  if (value < 1000) return String(Math.round(value));
23
23
  const divisor = value >= 1e6 ? 1e6 : 1000;
24
24
  return `${Number((value / divisor).toFixed(1))}${divisor === 1e6 ? "M" : "k"}`;
25
25
  }
26
+ /** Session age to the minute: `<1m`, `35m`, `2h 6m`, `3d 2h`. */
27
+ export function formatSessionAge(minutes: number): string {
28
+ if (minutes < 1) return "<1m";
29
+ if (minutes < 60) return `${minutes}m`;
30
+ if (minutes < 1440) return `${Math.floor(minutes / 60)}h ${minutes % 60}m`;
31
+ return `${Math.floor(minutes / 1440)}d ${Math.floor(minutes % 1440 / 60)}h`;
32
+ }
26
33
  function contextBar(percent: number | null, ascii: boolean): string {
27
34
  const width = 10;
28
35
  if (percent === null || !Number.isFinite(percent)) return `${"?".repeat(width)} ?%`;
@@ -71,6 +78,7 @@ function segmentText(id: SegmentId, data: StatuslineSnapshot, config: Statusline
71
78
  return `${tokens === null ? "?" : formatTokens(tokens)}/${capacity}(${percent === null ? "?" : Number(percent.toFixed(1))}%)`;
72
79
  }
73
80
  case "quota": return renderQuota(data.quota, config.icons === "ascii");
81
+ case "session": return data.sessionMinutes === null ? undefined : formatSessionAge(data.sessionMinutes);
74
82
  case "cost": return usage.cost.toFixed(3);
75
83
  case "input": return formatTokens(usage.input);
76
84
  case "output": return formatTokens(usage.output);
@@ -80,14 +88,14 @@ function segmentText(id: SegmentId, data: StatuslineSnapshot, config: Statusline
80
88
  case "statuses": return [...data.statuses.values()].map(cleanText).filter(Boolean).join(" · ") || undefined;
81
89
  }
82
90
  }
91
+ function usageColor(percent: number): ColorValue { return percent > 90 ? "error" : percent > 70 ? "warning" : "accent"; }
83
92
  function defaultColor(id: SegmentId, data: StatuslineSnapshot): ColorValue {
84
93
  if (id === "context") {
85
94
  if ((data.context.percent ?? 0) > 90) return "error";
86
95
  if ((data.context.percent ?? 0) > 70) return "warning";
87
96
  }
88
97
  if (id === "quota") {
89
- const used = Math.max(data.quota?.primary?.usedPercent ?? 0, data.quota?.secondary?.usedPercent ?? 0);
90
- return used > 90 ? "error" : used > 70 ? "warning" : "accent";
98
+ return usageColor(Math.max(data.quota?.primary?.usedPercent ?? 0, data.quota?.secondary?.usedPercent ?? 0));
91
99
  }
92
100
  if (id === "git") {
93
101
  if (data.git.conflicts) return "error";
@@ -114,12 +122,14 @@ interface Part {
114
122
  foreground: ColorValue;
115
123
  background?: ColorValue;
116
124
  thinking?: { text: string; foreground: ColorValue | "rainbow" };
125
+ /** Multi-colored body; `text` remains its plain equivalent. */
126
+ content?: (style: { fg: ReturnType<typeof color>; bg?: ReturnType<typeof color> }) => string;
117
127
  }
118
128
  function renderPart(part: Part, theme: RenderTheme): string {
119
129
  const bg = part.background ? color(part.background, theme) : undefined;
120
130
  const style = { fg: color(part.foreground, theme), ...(bg ? { bg } : {}) };
121
131
  const icon = part.icon ? theme.style(`${part.icon} `, { ...style, fg: color(part.config.iconColor ?? part.foreground, theme) }) : "";
122
- const text = theme.style(part.text, style);
132
+ const text = part.content ? part.content(style) : theme.style(part.text, style);
123
133
  let suffix = "";
124
134
  if (part.thinking) {
125
135
  const { text: level, foreground } = part.thinking;
@@ -154,12 +164,38 @@ function joinParts(parts: Part[], config: StatuslineConfig, theme: RenderTheme):
154
164
  }).join("");
155
165
  }
156
166
 
167
+ /** Each window colors its own bar and percentage; labels, countdowns and separators recede. */
168
+ function setQuota(part: Part, data: StatuslineSnapshot, config: StatuslineConfig, theme: RenderTheme, detail: QuotaDetail): void {
169
+ const ascii = config.icons === "ascii";
170
+ const pieces = quotaPieces(data.quota, ascii, detail) ?? [];
171
+ part.text = renderQuota(data.quota, ascii, detail) ?? "";
172
+ part.content = (style) => {
173
+ const paint = (text: string, value: ColorValue) => theme.style(text, { ...style, fg: color(value, theme) });
174
+ return pieces.map((piece) => {
175
+ const used = part.config.color ?? usageColor(piece.usedPercent);
176
+ return [
177
+ piece.label && paint(piece.label, "dim"), piece.bar && paint(piece.bar, used),
178
+ paint(piece.percent, used), piece.reset && paint(piece.reset, "muted"),
179
+ ].filter(Boolean).join(theme.style(" ", style));
180
+ }).join(paint(quotaSeparator(ascii), "dim"));
181
+ };
182
+ }
183
+ /** Session-wide values for the runtime row: dim icon, muted value. */
184
+ function sessionText(segment: SegmentConfig, data: StatuslineSnapshot, config: StatuslineConfig, theme: RenderTheme): string | undefined {
185
+ const icon = cleanText(segment.icon ?? ICONS[config.icons][segment.id] ?? "");
186
+ const value = segmentText(segment.id, data, config);
187
+ if (value === undefined) return undefined;
188
+ const styled = theme.style(value, { fg: color(segment.color ?? "muted", theme) });
189
+ return icon ? `${theme.style(icon, { fg: color(segment.iconColor ?? "dim", theme) })} ${styled}` : styled;
190
+ }
191
+
157
192
  /** Pure terminal rendering: no disk reads, processes or session traversal. */
158
193
  export function renderFooter(width: number, data: StatuslineSnapshot, config: StatuslineConfig, theme: RenderTheme): string[] {
159
194
  width = Math.max(0, Math.floor(width));
160
195
  if (width === 0) return [];
161
196
  const parts: Part[] = [];
162
197
  let secondary: Part | undefined;
198
+ const sessionRow: Partial<Record<"session" | "tokens", string>> = {};
163
199
  // CLIProxyAPI's published `tps` status is display text only.
164
200
  const tps = cleanText(data.statuses.get("tps") ?? "");
165
201
  const elapsedStatus = config.segments.some((s) => s.id === "statuses" && s.enabled) && /^Elapsed \d+[dhms](?: \d+[hms])*$/.test(tps) ? tps : undefined;
@@ -167,6 +203,7 @@ export function renderFooter(width: number, data: StatuslineSnapshot, config: St
167
203
  const thinking = config.segments.find((segment) => segment.id === "thinking");
168
204
  for (const segment of config.segments) {
169
205
  if (!segment.enabled) continue;
206
+ if (segment.id === "session" || segment.id === "tokens") { sessionRow[segment.id] = sessionText(segment, data, config, theme); continue; }
170
207
  const raw = segmentText(segment.id, segment.id === "statuses" ? { ...data, statuses } : data, config);
171
208
  if (raw === undefined) continue;
172
209
  let text = cleanText(raw);
@@ -179,6 +216,7 @@ export function renderFooter(width: number, data: StatuslineSnapshot, config: St
179
216
  foreground: thinking.color ?? (["high", "xhigh", "max"].includes(data.thinking) ? "rainbow" : defaultColor("thinking", data)),
180
217
  };
181
218
  }
219
+ if (segment.id === "quota") setQuota(part, data, config, theme, "full");
182
220
  if (segment.id === "statuses") secondary = part;
183
221
  else parts.push(part);
184
222
  }
@@ -206,7 +244,7 @@ export function renderFooter(width: number, data: StatuslineSnapshot, config: St
206
244
  const quota = parts.find((part) => part.config.id === "quota");
207
245
  if (quota && visibleWidth(line) > width) {
208
246
  for (const detail of ["bars", "percent"] as const) {
209
- quota.text = renderQuota(data.quota, config.icons === "ascii", detail)!;
247
+ setQuota(quota, data, config, theme, detail);
210
248
  line = joinParts(parts, config, theme);
211
249
  if (visibleWidth(line) <= width) break;
212
250
  }
@@ -217,8 +255,10 @@ export function renderFooter(width: number, data: StatuslineSnapshot, config: St
217
255
  }
218
256
  const lines: string[] = [];
219
257
  if (parts.length) lines.push(truncateToWidth(line, width, ellipsis));
220
- const secondLine = renderRuntime(width, data, config, theme, secondary ? renderPart(secondary, theme) : undefined, elapsedStatus);
221
- if (secondLine) lines.push(secondLine);
258
+ const tools = renderTools(width, data, config, theme);
259
+ if (tools) lines.push(tools);
260
+ const runtime = renderRuntime(width, data, config, theme, { statuses: secondary ? renderPart(secondary, theme) : undefined, ...sessionRow, elapsedStatus });
261
+ if (runtime) lines.push(runtime);
222
262
  return lines;
223
263
  }
224
264
 
@@ -238,8 +278,12 @@ export function sampleSnapshot(): StatuslineSnapshot {
238
278
  context: { tokens: 23800, contextWindow: 200000, percent: 11.9 },
239
279
  usage: { ...emptyUsage(), input: 32000, output: 5400, cacheRead: 12000, cost: 0.12 },
240
280
  git: { ...emptyGit("repository"), branch: "main", unstaged: 2, ahead: 2 },
241
- statuses: new Map([["example", "Example extension status"]]),
242
- runtime: { runId: "example", status: "Running", elapsedMs: 28000, turns: 3, toolCalls: 2, tools: [], awaitingInput: false, noContentMs: 0, usage: { ...emptyUsage(), output: 1260 }, avg: 45, cache: 0.86 },
281
+ statuses: new Map([["example", "Example extension status"]]), sessionMinutes: 126,
282
+ runtime: {
283
+ runId: "example", status: "Running", elapsedMs: 28000, turns: 3, toolCalls: 8, awaitingInput: false, noContentMs: null, usage: { ...emptyUsage(), output: 1260 }, avg: 45, cache: 0.86,
284
+ tools: [{ name: "bash", target: "npm test", elapsedMs: 12000 }],
285
+ completed: [{ name: "read", ok: 5, failed: 0 }, { name: "edit", ok: 2, failed: 0 }],
286
+ },
243
287
  compaction: { active: false, elapsedMs: 0, count: 1, showFailure: false },
244
288
  };
245
289
  }
@@ -1,6 +1,6 @@
1
1
  import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
2
2
  import type { RenderTheme } from "./render.ts";
3
- import { cleanText } from "./text.ts";
3
+ import type { RuntimeSnapshot } from "./runtime.ts";
4
4
  import type { StatuslineConfig, StatuslineSnapshot } from "./types.ts";
5
5
 
6
6
  export function seconds(ms: number): string { return `${Math.floor(ms / 1000)}s`; }
@@ -13,50 +13,126 @@ export function elapsed(ms: number): string {
13
13
  }
14
14
  return parts.join(" ");
15
15
  }
16
- interface Part { id: string; text: string; color?: "text" | "muted" | "warning" | "error" | "success"; styled?: string }
16
+ /** Tool timers stay narrow: `12s`, `1m5s`. */
17
+ function short(ms: number): string {
18
+ const total = Math.floor(ms / 1000);
19
+ return total < 60 ? `${total}s` : `${Math.floor(total / 60)}m${total % 60}s`;
20
+ }
21
+
22
+ type Color = "text" | "muted" | "dim" | "accent" | "success" | "warning" | "error";
23
+ type Span = [text: string, color: Color];
24
+ interface Part { id: string; spans: Span[]; styled?: string }
25
+
26
+ function draw(parts: Part[], separator: string, theme: RenderTheme): string {
27
+ return parts.map((part) => part.styled ?? part.spans.map(([text, color]) => theme.style(text, { fg: theme.colors[color] })).join(""))
28
+ .join(theme.style(separator, { fg: theme.colors.dim }));
29
+ }
30
+ function fit(parts: Part[], dropOrder: string[], width: number, separator: string, theme: RenderTheme, ellipsis: string): string | undefined {
31
+ let line = draw(parts, separator, theme);
32
+ for (const id of dropOrder) {
33
+ if (visibleWidth(line) <= width) break;
34
+ const index = parts.findIndex((part) => part.id === id);
35
+ if (index !== -1) { parts.splice(index, 1); line = draw(parts, separator, theme); }
36
+ }
37
+ return parts.length ? truncateToWidth(line, width, ellipsis) : undefined;
38
+ }
39
+
40
+ const STATUS: Partial<Record<RuntimeSnapshot["status"], { icon: string; ascii: string; color: Color }>> = {
41
+ Running: { icon: "●", ascii: "*", color: "muted" },
42
+ Done: { icon: "✓", ascii: "ok", color: "muted" },
43
+ Failed: { icon: "✗", ascii: "x", color: "error" },
44
+ Cancelled: { icon: "⊘", ascii: "-", color: "muted" },
45
+ };
17
46
 
18
- /** Layout consumes snapshots only; width decisions use terminal cells, including ANSI. */
19
- export function renderRuntime(width: number, data: StatuslineSnapshot, config: StatuslineConfig, theme: RenderTheme, extensionStatus?: string, elapsedStatus?: string): string | undefined {
47
+ export interface RuntimeExtras {
48
+ /** Other extensions' statuses, already styled. */
49
+ statuses?: string;
50
+ /** Session age, already styled. */
51
+ session?: string;
52
+ /** Session token total, already styled. */
53
+ tokens?: string;
54
+ /** A `tps` extension status of the form `Elapsed 5m 42s`. */
55
+ elapsedStatus?: string;
56
+ }
57
+
58
+ /**
59
+ * The bottom row: run status and duration, run metrics, then session age, tokens and extension statuses.
60
+ * It stays muted so it does not compete with the editor; only problems (failure, waits, low cache) are colored.
61
+ */
62
+ export function renderRuntime(width: number, data: StatuslineSnapshot, config: StatuslineConfig, theme: RenderTheme, extras: RuntimeExtras = {}): string | undefined {
20
63
  const parts: Part[] = [];
21
64
  const runtime = data.runtime, compact = data.compaction;
22
- const enabled = config.runtime.enabled;
23
- const add = (id: string, text: string, color?: Part["color"]) => parts.push({ id, text, color });
24
- if (elapsedStatus) add("elapsed", elapsedStatus);
25
- else if (enabled && config.runtime.status && runtime?.runId) add("elapsed", `Elapsed ${elapsed(runtime.elapsedMs)}`);
26
- if (enabled && compact?.active) {
27
- add("status", `${config.icons === "ascii" ? "Compacting..." : "Compacting…"} ${seconds(compact.elapsedMs)}`, "warning");
28
- if (config.runtime.counts && compact.count > 0) add("compactions", `Compactions ${compact.count}`);
29
- } else {
30
- if (enabled && runtime) {
31
- if (config.runtime.status) {
32
- const failure = compact?.showFailure && runtime.status !== "Running" ? `Compaction ${compact.last?.status}` : undefined;
33
- if (failure) add("status", failure, "error");
34
- }
35
- let busy = false;
36
- if (runtime.awaitingInput) { add("activity", "Awaiting input", "warning"); busy = true; }
37
- else if (config.runtime.tools && runtime.tools.length) {
38
- add("activity", runtime.tools.length > 1 ? `Tools ${runtime.tools.length} active` : `Tool ${cleanText(runtime.tools[0]!.name).slice(0, 40)} ${seconds(runtime.tools[0]!.elapsedMs)}`);
39
- busy = true;
40
- } else if (config.runtime.noContent && runtime.noContentMs !== null && runtime.noContentMs >= config.runtime.noContentSeconds * 1000) {
41
- add("activity", `No content ${seconds(runtime.noContentMs)}`); busy = true;
42
- }
43
- if (!busy) {
44
- if (config.runtime.avg && runtime.avg !== null) add("avg", `Avg ${Math.round(runtime.avg)} tok/s`);
45
- if (config.runtime.cache && runtime.cache !== null) add("cache", `Cache ${Math.round(runtime.cache * 100)}%`);
46
- }
47
- if (config.runtime.counts && runtime.runId) add("turns", `Turns ${runtime.turns}`);
65
+ const enabled = config.runtime.enabled, ascii = config.icons === "ascii";
66
+ const add = (id: string, ...spans: Span[]) => parts.push({ id, spans });
67
+ // Label first, like `avg` and `cache`: `turns 4`, `compactions 1`.
68
+ const count = (id: "turns" | "compactions", value: number) => add(id, [`${id} `, "dim"], [String(value), "muted"]);
69
+ const duration = extras.elapsedStatus?.replace(/^Elapsed /, "") ?? (runtime?.runId ? elapsed(runtime.elapsedMs) : undefined);
70
+ const state = enabled && config.runtime.status && runtime?.runId ? STATUS[runtime.status] : undefined;
71
+ if (state && duration) add("elapsed", [ascii ? state.ascii : state.icon, state.color], [` ${duration}`, "muted"]);
72
+ else if (extras.elapsedStatus) add("elapsed", ["elapsed ", "dim"], [duration!, "muted"]);
73
+ const compacting = enabled && !!compact?.active;
74
+ if (compacting) {
75
+ add("activity", [`${ascii ? "compacting..." : "compacting…"} ${seconds(compact!.elapsedMs)}`, "warning"]);
76
+ } else if (enabled && runtime) {
77
+ if (config.runtime.status && compact?.showFailure && runtime.status !== "Running") add("failure", [`compaction ${compact.last?.status}`, "error"]);
78
+ if (runtime.awaitingInput) add("activity", ["awaiting input", "warning"]);
79
+ else if (config.runtime.noContent && runtime.noContentMs !== null && runtime.noContentMs >= config.runtime.noContentSeconds * 1000) {
80
+ add("activity", [`no content ${seconds(runtime.noContentMs)}`, "warning"]);
48
81
  }
49
- if (enabled && config.runtime.counts && compact && compact.count > 0) add("compactions", `Compactions ${compact.count}`);
50
- if (extensionStatus) parts.push({ id: "statuses", text: extensionStatus, styled: extensionStatus });
82
+ if (config.runtime.avg && runtime.avg !== null) add("avg", ["avg ", "dim"], [`${Math.round(runtime.avg)} tok/s`, "muted"]);
83
+ if (config.runtime.cache && runtime.cache !== null) {
84
+ const percent = Math.round(runtime.cache * 100);
85
+ add("cache", ["cache ", "dim"], [`${percent}%`, percent < 50 ? "warning" : "muted"]);
86
+ }
87
+ if (config.runtime.counts && runtime.runId) count("turns", runtime.turns);
51
88
  }
52
- const separator = config.icons === "ascii" ? " | " : " · ";
53
- const draw = () => parts.map((part) => part.styled ?? theme.style(part.text, { fg: theme.colors[part.color ?? "muted"] })).join(theme.style(separator, { fg: theme.colors.dim }));
54
- let line = draw();
55
- for (const id of ["statuses", "cache", "avg", "compactions", "turns", "activity"]) {
56
- if (visibleWidth(line) <= width) break;
57
- const index = parts.findIndex((part) => part.id === id);
58
- if (index !== -1) parts.splice(index, 1);
59
- line = draw();
89
+ if (enabled && config.runtime.counts && compact && compact.count > 0) count("compactions", compact.count);
90
+ if (extras.session) parts.push({ id: "session", spans: [], styled: extras.session });
91
+ if (extras.tokens) parts.push({ id: "tokens", spans: [], styled: extras.tokens });
92
+ if (extras.statuses && !compacting) parts.push({ id: "statuses", spans: [], styled: extras.statuses });
93
+ return fit(parts, ["statuses", "cache", "avg", "compactions", "session", "tokens", "turns", "activity", "failure"], width, ascii ? " | " : " · ", theme, ascii ? "..." : "…");
94
+ }
95
+
96
+ /** `◐ bash npm test 12s · ✓ read ×5 · ✗ bash ×1 · +2`: present while the run has used tools. */
97
+ export function renderTools(width: number, data: StatuslineSnapshot, config: StatuslineConfig, theme: RenderTheme): string | undefined {
98
+ const runtime = data.runtime;
99
+ if (!config.runtime.enabled || !config.runtime.tools || !runtime || (!runtime.tools.length && !runtime.completed.length)) return undefined;
100
+ const ascii = config.icons === "ascii";
101
+ const sym = ascii ? { run: ">", ok: "ok", fail: "x", times: "x" } : { run: "◐", ok: "✓", fail: "✗", times: "×" };
102
+ const running: { name: string; count: number; target?: string; elapsedMs: number }[] = [];
103
+ for (const tool of runtime.tools) {
104
+ const group = running.find((item) => item.name === tool.name);
105
+ if (!group) running.push({ name: tool.name, count: 1, target: tool.target, elapsedMs: tool.elapsedMs });
106
+ else { group.count++; group.target = undefined; group.elapsedMs = Math.max(group.elapsedMs, tool.elapsedMs); }
107
+ }
108
+ const ok = runtime.completed.filter((tool) => tool.ok).sort((a, b) => b.ok - a.ok);
109
+ const failed = runtime.completed.filter((tool) => tool.failed).sort((a, b) => b.failed - a.failed);
110
+ const build = (visible: number, targets: boolean, timers: boolean): Part[] => {
111
+ const parts: Part[] = running.slice(0, 2).map((group) => {
112
+ const spans: Span[] = [[sym.run, "warning"], [` ${group.name}`, "accent"]];
113
+ if (group.count > 1) spans.push([` ${sym.times}${group.count}`, "dim"]);
114
+ else if (targets && group.target) spans.push([` ${group.target}`, "muted"]);
115
+ if (timers && group.elapsedMs >= 1000) spans.push([` ${short(group.elapsedMs)}`, group.elapsedMs >= 30000 ? "warning" : "muted"]);
116
+ return { id: "running", spans };
117
+ });
118
+ const moreRunning = running.slice(2).reduce((total, group) => total + group.count, 0);
119
+ if (moreRunning) parts.push({ id: "running", spans: [[sym.run, "warning"], [` +${moreRunning}`, "dim"]] });
120
+ for (const tool of ok.slice(0, visible)) parts.push({ id: "ok", spans: [[sym.ok, "success"], [` ${tool.name}`, "muted"], [` ${sym.times}${tool.ok}`, "dim"]] });
121
+ for (const tool of failed) parts.push({ id: "failed", spans: [[sym.fail, "error"], [` ${tool.name}`, "muted"], [` ${sym.times}${tool.failed}`, "error"]] });
122
+ const hidden = ok.length - Math.min(visible, ok.length);
123
+ if (hidden) parts.push({ id: "more", spans: [[`+${hidden}`, "dim"]] });
124
+ return parts;
125
+ };
126
+ // Narrowing order: fold completed kinds, then drop targets, then timers; running names go last.
127
+ const max = config.runtime.toolsMaxVisible;
128
+ const attempts: [number, boolean, boolean][] = [];
129
+ for (let visible = max; visible >= 1; visible--) attempts.push([visible, true, true]);
130
+ attempts.push([1, false, true], [0, false, true], [0, false, false]);
131
+ const separator = ascii ? " | " : " · ";
132
+ let parts: Part[] = [];
133
+ for (const [visible, targets, timers] of attempts) {
134
+ parts = build(visible, targets, timers);
135
+ if (visibleWidth(draw(parts, separator, theme)) <= width) break;
60
136
  }
61
- return parts.length ? truncateToWidth(line, width, config.icons === "ascii" ? "..." : "…") : undefined;
137
+ return fit(parts, [], width, separator, theme, ascii ? "..." : "…");
62
138
  }
package/src/runtime.ts CHANGED
@@ -2,6 +2,7 @@ import { randomUUID } from "node:crypto";
2
2
  import type { AssistantMessage, AssistantMessageEvent } from "@earendil-works/pi-ai";
3
3
  import type { AgentActivityOutcome } from "@earendil-works/pi-coding-agent";
4
4
  import { cleanText } from "./text.ts";
5
+ import { toolTarget } from "./tools.ts";
5
6
  import { emptyUsage, readUsage } from "./usage.ts";
6
7
  import type { UsageTotals } from "./types.ts";
7
8
 
@@ -12,7 +13,10 @@ export interface RuntimeSnapshot {
12
13
  elapsedMs: number;
13
14
  turns: number;
14
15
  toolCalls: number;
15
- tools: { name: string; elapsedMs: number }[];
16
+ /** Running top-level tools in start order; nested calls are represented by their parent. */
17
+ tools: { name: string; target?: string; elapsedMs: number }[];
18
+ /** Finished calls this run, by tool name in first-seen order. */
19
+ completed: { name: string; ok: number; failed: number }[];
16
20
  awaitingInput: boolean;
17
21
  noContentMs: number | null;
18
22
  usage: UsageTotals | null;
@@ -30,7 +34,8 @@ export class RuntimeState {
30
34
  private outcome: AgentActivityOutcome = "completed";
31
35
  private aborted = false;
32
36
  private turns = 0;
33
- private tools = new Map<string, { name: string; start: number }>();
37
+ private tools = new Map<string, { name: string; target?: string; nested: boolean; start: number }>();
38
+ private completed = new Map<string, { ok: number; failed: number }>();
34
39
  private seenTools = new Set<string>();
35
40
  private prompts = 0;
36
41
  private modelActive = false;
@@ -45,7 +50,7 @@ export class RuntimeState {
45
50
  get id(): string | null { return this.runId; }
46
51
  reset(): void {
47
52
  this.runId = null; this.state = "Idle"; this.startMs = 0; this.endMs = 0;
48
- this.outcome = "completed"; this.aborted = false; this.turns = 0; this.tools.clear(); this.seenTools.clear();
53
+ this.outcome = "completed"; this.aborted = false; this.turns = 0; this.tools.clear(); this.completed.clear(); this.seenTools.clear();
49
54
  this.prompts = 0; this.modelActive = false; this.compacting = false;
50
55
  this.messages.clear(); this.messageAliases.clear(); this.activeMessage = undefined; this.sequence = 0;
51
56
  }
@@ -102,11 +107,22 @@ export class RuntimeState {
102
107
  if (!this.aborted) this.outcome = message.stopReason === "aborted" ? "aborted" : message.stopReason === "error" ? "error" : "completed";
103
108
  }
104
109
  }
105
- toolStart(id: string, name: string): void {
110
+ toolStart(id: string, name: string, args?: unknown, parentId?: string): void {
106
111
  if (!this.running || this.seenTools.has(id)) return;
107
- this.seenTools.add(id); this.tools.set(id, { name: cleanText(name).slice(0, 40) || "unknown", start: this.clock() });
112
+ const target = toolTarget(name, args);
113
+ this.seenTools.add(id);
114
+ this.tools.set(id, { name: cleanText(name).slice(0, 40) || "unknown", ...(target ? { target } : {}), nested: !!parentId, start: this.clock() });
115
+ }
116
+ toolEnd(id: string, isError = false): void {
117
+ const tool = this.tools.get(id);
118
+ if (!tool) return;
119
+ this.tools.delete(id);
120
+ // Calls interrupted by a user cancellation are not tool failures; the run status says so.
121
+ if (isError && this.aborted) return;
122
+ const count = this.completed.get(tool.name) ?? { ok: 0, failed: 0 };
123
+ if (isError) count.failed++; else count.ok++;
124
+ this.completed.set(tool.name, count);
108
125
  }
109
- toolEnd(id: string): void { this.tools.delete(id); }
110
126
  uiStart(): void { this.prompts++; }
111
127
  uiEnd(): void { this.prompts = Math.max(0, this.prompts - 1); this.lastContent = this.clock(); }
112
128
  compaction(active: boolean): void { this.compacting = active; this.lastContent = this.clock(); }
@@ -120,7 +136,9 @@ export class RuntimeState {
120
136
  return {
121
137
  runId: hidden ? null : this.runId, status: hidden ? "Idle" : this.state, elapsedMs,
122
138
  turns: hidden ? 0 : this.turns, toolCalls: hidden ? 0 : this.seenTools.size,
123
- tools: [...this.tools.values()].map((tool) => ({ name: tool.name, elapsedMs: Math.max(0, now - tool.start) })),
139
+ tools: [...this.tools.values()].filter((tool) => !tool.nested)
140
+ .map((tool) => ({ name: tool.name, ...(tool.target ? { target: tool.target } : {}), elapsedMs: Math.max(0, now - tool.start) })),
141
+ completed: hidden ? [] : [...this.completed].map(([name, count]) => ({ name, ...count })),
124
142
  awaitingInput: this.prompts > 0,
125
143
  noContentMs: this.running && this.modelActive && !this.tools.size && !this.prompts && !this.compacting ? Math.max(0, now - this.lastContent) : null,
126
144
  usage, avg: usage && elapsedMs > 0 ? usage.output / (elapsedMs / 1000) : null,
package/src/session.ts CHANGED
@@ -10,6 +10,12 @@ import { RuntimeState } from "./runtime.ts";
10
10
  import { CompactionState } from "./compaction.ts";
11
11
  import { QuotaState } from "./quota.ts";
12
12
 
13
+ /** The header's creation time; hidden rather than guessed when missing, malformed or in the future. */
14
+ export function sessionStart(timestamp: string | undefined, now = Date.now()): number | null {
15
+ const ms = timestamp ? Date.parse(timestamp) : NaN;
16
+ return Number.isFinite(ms) && ms <= now + 60000 ? ms : null;
17
+ }
18
+
13
19
  export class FooterSession {
14
20
  readonly runtime = new RuntimeState();
15
21
  readonly compaction = new CompactionState();
@@ -29,6 +35,7 @@ export class FooterSession {
29
35
  private statsKey = "";
30
36
  private displayKey = "";
31
37
  private context: StatuslineSnapshot["context"] = { tokens: null, contextWindow: 0, percent: null };
38
+ private sessionStartMs: number | null = null;
32
39
  private readonly gitReader: GitReader | undefined;
33
40
  private signal: AbortSignal | undefined;
34
41
  private readonly onAbort = () => { this.runtime.observeAbort(); this.schedule(true); };
@@ -123,6 +130,7 @@ export class FooterSession {
123
130
  const entries = manager.getEntries();
124
131
  this.usage.update(entries);
125
132
  this.compaction.update(entries);
133
+ this.sessionStartMs = sessionStart(manager.getHeader()?.timestamp);
126
134
  const context = this.ctx.getContextUsage();
127
135
  this.context = context ?? { tokens: null, contextWindow: this.ctx.model?.contextWindow ?? 0, percent: null };
128
136
  }
@@ -142,6 +150,8 @@ export class FooterSession {
142
150
  thinking: this.ctx.thinkingLevel ?? "off", cwd: this.ctx.cwd, home: homedir(),
143
151
  context: this.context, usage: this.usage.snapshot(), quota: this.quota.snapshot(this.ctx.model), git: this.git,
144
152
  statuses: this.provider?.getExtensionStatuses() ?? new Map(),
153
+ // Minute resolution keeps an idle footer from repainting every second.
154
+ sessionMinutes: this.sessionStartMs === null ? null : Math.floor(Math.max(0, Date.now() - this.sessionStartMs) / 60000),
145
155
  runtime: this.runtime.snapshot(this.config.runtime.retainSummary), compaction: this.compaction.snapshot(),
146
156
  };
147
157
  }
package/src/tools.ts ADDED
@@ -0,0 +1,43 @@
1
+ import { basename } from "node:path";
2
+ import { visibleWidth } from "@earendil-works/pi-tui";
3
+ import { cleanText } from "./text.ts";
4
+
5
+ function arg(args: unknown, key: string): string | undefined {
6
+ if (typeof args !== "object" || args === null) return undefined;
7
+ const value = (args as Record<string, unknown>)[key];
8
+ return typeof value === "string" ? value : undefined;
9
+ }
10
+ /** Plain-text truncation: targets are styled later, so no escape codes here. */
11
+ function fit(text: string | undefined, width: number): string | undefined {
12
+ if (!text || visibleWidth(text) <= width) return text || undefined;
13
+ let result = "";
14
+ for (const character of text) {
15
+ if (visibleWidth(result + character) > width - 1) break;
16
+ result += character;
17
+ }
18
+ return `${result}…`;
19
+ }
20
+ function fileName(path: string | undefined): string | undefined {
21
+ const name = path ? basename(cleanText(path).replace(/[\\/]+$/, "")) : "";
22
+ return name && name !== "." ? name : undefined;
23
+ }
24
+ /** `cd dir && FOO=1 npm test` → `npm test`: the part that says what is running. */
25
+ function commandSummary(command: string): string | undefined {
26
+ let text = cleanText(command.split(/\r?\n/).find((line) => line.trim()) ?? "");
27
+ for (let previous = ""; previous !== text;) {
28
+ previous = text;
29
+ text = text.replace(/^cd\s+(?:"[^"]*"|'[^']*'|\S+)\s*(?:&&|;)\s*/, "").replace(/^[A-Za-z_][A-Za-z0-9_]*=(?:"[^"]*"|'[^']*'|\S*)\s+/, "");
30
+ }
31
+ return text || undefined;
32
+ }
33
+
34
+ /** A short, sanitized description of what a built-in tool call is working on. */
35
+ export function toolTarget(name: string, args: unknown): string | undefined {
36
+ switch (name) {
37
+ case "bash": case "powershell": { const command = arg(args, "command"); return fit(command && commandSummary(command), 24); }
38
+ case "read": case "edit": case "write": return fit(fileName(arg(args, "path")), 24);
39
+ case "grep": case "find": { const pattern = arg(args, "pattern"); const text = pattern && cleanText(pattern); return text ? `"${fit(text, 16)}"` : undefined; }
40
+ case "ls": { const dir = fileName(arg(args, "path")); return dir ? `${fit(dir, 23)}/` : undefined; }
41
+ default: return undefined;
42
+ }
43
+ }
package/src/types.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import type { ThemeColor } from "@earendil-works/pi-coding-agent";
2
2
 
3
- export const SEGMENT_IDS = ["model", "thinking", "context", "quota", "directory", "git", "cost", "input", "output", "tokens", "cacheRead", "cacheWrite", "statuses"] as const;
3
+ export const SEGMENT_IDS = ["model", "thinking", "context", "quota", "directory", "git", "cost", "input", "output", "session", "tokens", "cacheRead", "cacheWrite", "statuses"] as const;
4
4
  export type SegmentId = typeof SEGMENT_IDS[number];
5
5
  export type ColorValue = ThemeColor | `#${string}`;
6
6
  export type Preset = "powerline";
@@ -15,6 +15,8 @@ export interface RuntimeConfig {
15
15
  cache: boolean;
16
16
  counts: boolean;
17
17
  retainSummary: boolean;
18
+ /** Completed tool kinds shown before folding into `+N` (1–8). */
19
+ toolsMaxVisible: number;
18
20
  }
19
21
  export interface SegmentConfig {
20
22
  id: SegmentId;
@@ -68,6 +70,8 @@ export interface StatuslineSnapshot {
68
70
  quota?: import("./quota.ts").QuotaSnapshot;
69
71
  git: GitState;
70
72
  statuses: ReadonlyMap<string, string>;
73
+ /** Whole minutes since the session file was created; null when unknown. */
74
+ sessionMinutes: number | null;
71
75
  runtime?: import("./runtime.ts").RuntimeSnapshot;
72
76
  compaction?: import("./compaction.ts").CompactionSnapshot;
73
77
  }