pi-path-bar 0.4.2 → 0.5.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-path-bar",
3
- "version": "0.4.2",
3
+ "version": "0.5.1",
4
4
  "description": "A Pi extension for compact paths, folder aliases, and theme-aware Git status",
5
5
  "keywords": [
6
6
  "footer",
@@ -39,8 +39,8 @@
39
39
  "prepublishOnly": "npm run check && npm test"
40
40
  },
41
41
  "devDependencies": {
42
- "@earendil-works/pi-coding-agent": "^1.5.0",
43
- "@earendil-works/pi-tui": "^1.5.0",
42
+ "@earendil-works/pi-coding-agent": "^1.6.0",
43
+ "@earendil-works/pi-tui": "^1.6.0",
44
44
  "@types/node": "^26.6.6",
45
45
  "typescript": "^7.0.2"
46
46
  },
package/src/config.ts CHANGED
@@ -2,18 +2,24 @@ import { mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync }
2
2
  import { homedir } from "node:os";
3
3
  import { dirname, isAbsolute, join, resolve } from "node:path";
4
4
  import { randomUUID } from "node:crypto";
5
+ import { SEGMENT_ID } from "./segments.ts";
5
6
 
6
7
  export type PathMode = "short" | "auto" | "full" | "native";
7
8
  export interface FolderAlias { path: string; name: string }
8
9
  export interface Config {
9
10
  mode: PathMode;
11
+ minimal: boolean;
10
12
  icon: boolean;
11
13
  branch: boolean;
12
14
  session: boolean;
13
15
  timeFormat: "24h" | "12h";
16
+ /** Left-to-right order of the footer segments on the path line; "clock" is the built-in time. */
17
+ segments: string[];
18
+ /** Hidden segment ids (built-in clock, Type 1 adapted extensions, and Type 2 path-bar:* segments). */
19
+ hiddenSegments: string[];
14
20
  aliases: FolderAlias[];
15
21
  }
16
- export const defaults = (): Config => ({ mode: "short", icon: true, branch: true, session: true, timeFormat: "24h", aliases: [] });
22
+ export const defaults = (): Config => ({ mode: "short", minimal: true, icon: true, branch: true, session: true, timeFormat: "24h", segments: [], hiddenSegments: [], aliases: [] });
17
23
 
18
24
  export function aliasName(value: string): string {
19
25
  const name = value.trim();
@@ -47,7 +53,19 @@ export function validateConfig(value: unknown): Config {
47
53
  if (data.timeFormat !== "24h" && data.timeFormat !== "12h") throw new Error("Invalid time format. Use 24h or 12h.");
48
54
  config.timeFormat = data.timeFormat;
49
55
  }
50
- for (const key of ["icon", "branch", "session"] as const) {
56
+ if (data.segments !== undefined) {
57
+ if (!Array.isArray(data.segments) || data.segments.some((id: unknown) => typeof id !== "string" || !SEGMENT_ID.test(id))) {
58
+ throw new Error("segments must be an array of segment ids, for example [\"net\", \"clock\"]");
59
+ }
60
+ config.segments = [...new Set(data.segments as string[])];
61
+ }
62
+ if (data.hiddenSegments !== undefined) {
63
+ if (!Array.isArray(data.hiddenSegments) || data.hiddenSegments.some((id: unknown) => typeof id !== "string" || !SEGMENT_ID.test(id))) {
64
+ throw new Error("hiddenSegments must be an array of segment ids, for example [\"clock\", \"ssh\"]");
65
+ }
66
+ config.hiddenSegments = [...new Set(data.hiddenSegments as string[])];
67
+ }
68
+ for (const key of ["minimal", "icon", "branch", "session"] as const) {
51
69
  if (data[key] === undefined) continue;
52
70
  if (typeof data[key] !== "boolean") throw new Error(`${key} must be a boolean.`);
53
71
  config[key] = data[key];
package/src/index.ts CHANGED
@@ -1,32 +1,196 @@
1
1
  import { homedir } from "node:os";
2
2
  import { join } from "node:path";
3
- import { getAgentDir } from "@earendil-works/pi-coding-agent";
3
+ import { getAgentDir, type ExtensionAPI, type ExtensionContext, type ReadonlyFooterDataProvider } from "@earendil-works/pi-coding-agent";
4
+ type EditorFactory = NonNullable<Parameters<ExtensionContext["ui"]["setEditorComponent"]>[0]>;
5
+ import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
4
6
  import { ConfigStore, defaults, type Config } from "./config.ts";
5
- import { openSettings } from "./settings.ts";
6
7
  import { gitColor, gitText, watchGit } from "./git.ts";
7
- import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
8
- import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
8
+ import { MinimalEditor, type MinimalBorderTheme, type MinimalEditorSource, type UsageTotals } from "./minimal.ts";
9
9
  import { directoryLine, resolveDisplayPath } from "./path.ts";
10
+ import { CLOCK, SEGMENT_KEY, classifyStatuses, resolveOrder, segmentEntries } from "./segments.ts";
11
+ import { openSettings } from "./settings.ts";
10
12
 
11
13
  const tokens = (n: number) => n < 1000 ? String(n) : n < 1e6 ? `${(n / 1000).toFixed(1)}k` : `${(n / 1e6).toFixed(1)}M`;
12
14
 
15
+ interface SessionStats {
16
+ totals: UsageTotals;
17
+ hitRate?: number;
18
+ }
19
+
20
+ interface StatsCache extends SessionStats {
21
+ sessionId?: string;
22
+ leafId?: string | null;
23
+ count: number;
24
+ last: unknown;
25
+ }
26
+
27
+ function createStatsReader() {
28
+ let cache: StatsCache | undefined;
29
+ return (ctx: ExtensionContext): SessionStats => {
30
+ const sm = ctx.sessionManager as ExtensionContext["sessionManager"] & {
31
+ getSessionId?: () => string;
32
+ getLeafId?: () => string | null;
33
+ };
34
+ const entries = sm.getEntries();
35
+ const sessionId = sm.getSessionId?.();
36
+ const leafId = sm.getLeafId?.();
37
+ const last = entries[entries.length - 1];
38
+ if (cache && cache.sessionId === sessionId && cache.leafId === leafId && cache.count === entries.length && cache.last === last) {
39
+ return cache;
40
+ }
41
+ const totals: UsageTotals = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0 };
42
+ let hitRate: number | undefined;
43
+ // Include usage before compaction and usage from tools and summaries.
44
+ for (const entry of entries) {
45
+ const usage = entry.type === "message"
46
+ ? (entry.message.role === "assistant" || entry.message.role === "toolResult" ? entry.message.usage : undefined)
47
+ : (entry.type === "usage" || entry.type === "compaction" || entry.type === "branch_summary" ? entry.usage : undefined);
48
+ if (!usage) continue;
49
+ totals.input += usage.input ?? 0;
50
+ totals.output += usage.output ?? 0;
51
+ totals.cacheRead += usage.cacheRead ?? 0;
52
+ totals.cacheWrite += usage.cacheWrite ?? 0;
53
+ totals.cost += usage.cost?.total ?? 0;
54
+ if (entry.type === "message" && entry.message.role === "assistant") {
55
+ const prompt = usage.input + usage.cacheRead + usage.cacheWrite;
56
+ hitRate = prompt > 0 ? usage.cacheRead / prompt * 100 : undefined;
57
+ }
58
+ }
59
+ cache = { sessionId, leafId, count: entries.length, last, totals, hitRate };
60
+ return cache;
61
+ };
62
+ }
63
+
13
64
  export default function (pi: ExtensionAPI, configFile = join(getAgentDir(), "pi-path-bar.json")) {
14
65
  const store = new ConfigStore(configFile, configFile === join(getAgentDir(), "pi-path-bar.json") ? join(getAgentDir(), "pi-show-dir.json") : undefined);
15
66
  let config = defaults();
67
+ const readStats = createStatsReader();
16
68
  const load = (ctx: ExtensionContext) => {
17
69
  try { config = store.load(); }
18
70
  catch (error) { ctx.ui.notify(`Cannot read ${store.file}: ${error instanceof Error ? error.message : String(error)}. The file will not be overwritten.`, "error"); }
19
71
  };
20
72
  let activeGit: ReturnType<typeof watchGit> | undefined;
21
73
  let disposeFooter: (() => void) | undefined;
74
+ let footerData: ReadonlyFooterDataProvider | undefined;
75
+ let activeTheme: MinimalBorderTheme | undefined;
76
+ let activeEditorFactory: EditorFactory | undefined;
77
+ let activeCtx: ExtensionContext | undefined;
78
+
79
+ const restoreEditor = (ctx?: ExtensionContext) => {
80
+ if (!activeEditorFactory) return;
81
+ const target = ctx ?? activeCtx;
82
+ if (target && target.ui.getEditorComponent?.() === activeEditorFactory) {
83
+ target.ui.setEditorComponent?.(undefined);
84
+ }
85
+ activeEditorFactory = undefined;
86
+ };
87
+
22
88
  const install = (ctx: ExtensionContext) => {
23
89
  disposeFooter?.();
24
90
  disposeFooter = undefined;
25
91
  if (ctx.mode !== "tui") return;
92
+ activeCtx = ctx;
93
+
94
+ if (config.minimal) {
95
+ ctx.ui.setFooter((tui, theme, data) => {
96
+ const monitor = config.branch ? watchGit(ctx.sessionManager.getCwd(), () => tui.requestRender()) : undefined;
97
+ activeGit = monitor;
98
+ footerData = data;
99
+ activeTheme = theme;
100
+ const unsubscribe = data.onBranchChange(() => { monitor?.refresh(); tui.requestRender(); });
101
+ let minute = Math.floor(Date.now() / 60_000);
102
+ const timer = setInterval(() => {
103
+ const next = Math.floor(Date.now() / 60_000);
104
+ if (next !== minute) { minute = next; tui.requestRender(); }
105
+ }, 1000);
106
+ timer.unref();
107
+ let disposed = false;
108
+ const dispose = () => {
109
+ if (disposed) return;
110
+ disposed = true;
111
+ clearInterval(timer);
112
+ unsubscribe();
113
+ monitor?.dispose();
114
+ if (activeGit === monitor) activeGit = undefined;
115
+ if (footerData === data) footerData = undefined;
116
+ };
117
+ disposeFooter = dispose;
118
+ return {
119
+ dispose,
120
+ invalidate() {},
121
+ render(width: number): string[] {
122
+ // Minimal mode hides the footer completely unless Type 3 (unknown) extension statuses exist.
123
+ const { unknown } = classifyStatuses(data.getExtensionStatuses());
124
+ if (!unknown.length) return [];
125
+ const text = unknown.map(([, value]) => value).join(" ");
126
+ return [truncateToWidth(text, width, "…")];
127
+ },
128
+ };
129
+ });
130
+
131
+ const borderTheme = (): MinimalBorderTheme => activeTheme ?? activeCtx?.ui.theme ?? { fg: (_color, text) => text };
132
+ const source: MinimalEditorSource = {
133
+ getTopInput: (indicator, borderColor) => {
134
+ const current = activeCtx ?? ctx;
135
+ const { totals, hitRate } = readStats(current);
136
+ const model = current.model;
137
+ const subscription = Boolean(model && (model.provider === "kimi-coding" || current.modelRegistry?.isUsingOAuth(model)));
138
+ const { slots } = classifyStatuses(footerData?.getExtensionStatuses() ?? new Map());
139
+ return {
140
+ indicator,
141
+ totals,
142
+ hitRate,
143
+ subscription,
144
+ sessionName: current.sessionManager.getSessionName(),
145
+ showSession: config.session,
146
+ timeFormat: config.timeFormat,
147
+ now: new Date(),
148
+ slots,
149
+ order: config.segments,
150
+ hidden: new Set(config.hiddenSegments),
151
+ theme: borderTheme(),
152
+ borderColor,
153
+ };
154
+ },
155
+ getBottomInput: (borderColor) => {
156
+ const current = activeCtx ?? ctx;
157
+ const display = resolveDisplayPath(current.sessionManager.getCwd(), homedir(), config.aliases);
158
+ const model = current.model;
159
+ const usage = current.getContextUsage();
160
+ return {
161
+ displayPath: display.path,
162
+ aliasName: display.aliasName,
163
+ pathMode: config.mode === "native" ? "short" : config.mode,
164
+ showIcon: config.icon,
165
+ showBranch: config.branch,
166
+ gitState: activeGit?.value ?? { kind: "none" },
167
+ fallbackBranch: footerData?.getGitBranch() ?? undefined,
168
+ modelId: model?.id,
169
+ reasoning: model?.reasoning,
170
+ thinkingLevel: pi.getThinkingLevel(),
171
+ contextPercent: usage?.percent,
172
+ contextWindow: usage?.contextWindow ?? model?.contextWindow ?? 0,
173
+ theme: borderTheme(),
174
+ borderColor,
175
+ };
176
+ },
177
+ };
178
+
179
+ if (!activeEditorFactory || ctx.ui.getEditorComponent?.() !== activeEditorFactory) {
180
+ const factory: EditorFactory = (tui, editorTheme, keybindings) => new MinimalEditor(tui, editorTheme, keybindings, source);
181
+ activeEditorFactory = factory;
182
+ ctx.ui.setEditorComponent?.(factory);
183
+ }
184
+ return;
185
+ }
186
+
187
+ restoreEditor(ctx);
26
188
  if (config.mode === "native") { ctx.ui.setFooter(undefined); return; }
27
189
  ctx.ui.setFooter((tui, theme, data) => {
28
190
  const monitor = config.branch ? watchGit(ctx.sessionManager.getCwd(), () => tui.requestRender()) : undefined;
29
191
  activeGit = monitor;
192
+ footerData = data;
193
+ activeTheme = theme;
30
194
  const unsubscribe = data.onBranchChange(() => { monitor?.refresh(); tui.requestRender(); });
31
195
  const clock = new Intl.DateTimeFormat("en-US", { hour: "2-digit", minute: "2-digit", hourCycle: config.timeFormat === "12h" ? "h12" : "h23" });
32
196
  let minute = Math.floor(Date.now() / 60_000);
@@ -43,6 +207,7 @@ export default function (pi: ExtensionAPI, configFile = join(getAgentDir(), "pi-
43
207
  unsubscribe();
44
208
  monitor?.dispose();
45
209
  if (activeGit === monitor) activeGit = undefined;
210
+ if (footerData === data) footerData = undefined;
46
211
  };
47
212
  disposeFooter = dispose;
48
213
  return {
@@ -55,10 +220,19 @@ export default function (pi: ExtensionAPI, configFile = join(getAgentDir(), "pi-
55
220
  const name = config.session ? ctx.sessionManager.getSessionName() : undefined;
56
221
  const suffix = `${gitSuffix}${name ? ` • ${name}` : ""}`;
57
222
  const display = resolveDisplayPath(ctx.sessionManager.getCwd(), homedir(), config.aliases);
58
- const time = clock.format(new Date());
59
- const timeWidth = visibleWidth(time);
60
- const showClock = width >= timeWidth + 3;
61
- const path = directoryLine(display.path, suffix, showClock ? width - timeWidth - 2 : width, {
223
+ const time = theme.fg("dim", clock.format(new Date()));
224
+ const entries = segmentEntries(data.getExtensionStatuses());
225
+ const hidden = new Set(config.hiddenSegments);
226
+ const group = resolveOrder(config.segments, entries.keys()).flatMap((id) => {
227
+ if (hidden.has(id)) return [];
228
+ const text = id === CLOCK ? time : entries.get(id) ?? "";
229
+ return text ? [text] : [];
230
+ });
231
+ // Narrow terminals drop from the right: the segment nearest the edge goes first.
232
+ while (group.length && visibleWidth(group.join(" ")) > width - 3) group.pop();
233
+ const groupText = group.join(theme.fg("dim", " "));
234
+ const groupWidth = visibleWidth(groupText);
235
+ const path = directoryLine(display.path, suffix, group.length ? width - groupWidth - 2 : width, {
62
236
  mode: config.mode === "native" ? "short" : config.mode,
63
237
  icon: config.icon,
64
238
  aliasName: display.aliasName,
@@ -68,26 +242,9 @@ export default function (pi: ExtensionAPI, configFile = join(getAgentDir(), "pi-
68
242
  suffix: (text) => theme.fg(gitColor(state), text.slice(0, gitSuffix.length)) + theme.fg("dim", text.slice(gitSuffix.length)),
69
243
  },
70
244
  });
71
- const lines = [showClock ? path + theme.fg("dim", " ".repeat(width - visibleWidth(path) - timeWidth) + time) : path];
245
+ const lines = [group.length ? path + theme.fg("dim", " ".repeat(width - visibleWidth(path) - groupWidth)) + groupText : path];
72
246
 
73
- const totals = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0 };
74
- let hitRate: number | undefined;
75
- // Include usage before compaction and usage from tools and summaries.
76
- for (const entry of ctx.sessionManager.getEntries()) {
77
- const usage = entry.type === "message"
78
- ? (entry.message.role === "assistant" || entry.message.role === "toolResult" ? entry.message.usage : undefined)
79
- : (entry.type === "usage" || entry.type === "compaction" || entry.type === "branch_summary" ? entry.usage : undefined);
80
- if (!usage) continue;
81
- totals.input += usage.input ?? 0;
82
- totals.output += usage.output ?? 0;
83
- totals.cacheRead += usage.cacheRead ?? 0;
84
- totals.cacheWrite += usage.cacheWrite ?? 0;
85
- totals.cost += usage.cost?.total ?? 0;
86
- if (entry.type === "message" && entry.message.role === "assistant") {
87
- const prompt = usage.input + usage.cacheRead + usage.cacheWrite;
88
- hitRate = prompt > 0 ? usage.cacheRead / prompt * 100 : undefined;
89
- }
90
- }
247
+ const { totals, hitRate } = readStats(ctx);
91
248
  const stats: string[] = [];
92
249
  for (const [key, prefix] of [["input", "↑"], ["output", "↓"], ["cacheRead", "R"], ["cacheWrite", "W"]] as const) {
93
250
  if (totals[key]) stats.push(`${prefix}${tokens(totals[key])}`);
@@ -111,7 +268,7 @@ export default function (pi: ExtensionAPI, configFile = join(getAgentDir(), "pi-
111
268
  right = available > 0 ? truncateToWidth(right, available, "…") : "";
112
269
  const padding = right ? " ".repeat(Math.max(2, width - visibleWidth(left) - visibleWidth(right))) : "";
113
270
  lines.push(theme.fg("dim", left) + theme.fg("dim", padding + right));
114
- const statuses = [...data.getExtensionStatuses()].sort(([a], [b]) => a.localeCompare(b));
271
+ const statuses = [...data.getExtensionStatuses()].filter(([key]) => !SEGMENT_KEY.test(key)).sort(([a], [b]) => a.localeCompare(b));
115
272
  if (statuses.length) {
116
273
  const text = statuses.map(([, value]) => value.replace(/[\r\n\t]/g, " ")).join(" ");
117
274
  lines.push(truncateToWidth(text, width, "…"));
@@ -124,18 +281,18 @@ export default function (pi: ExtensionAPI, configFile = join(getAgentDir(), "pi-
124
281
  pi.on("session_start", async (_event, ctx) => { load(ctx); install(ctx); });
125
282
  pi.on("tool_result", () => { activeGit?.refresh(); });
126
283
  pi.on("agent_end", () => { activeGit?.refresh(); });
127
- pi.on("session_shutdown", () => { disposeFooter?.(); disposeFooter = undefined; });
284
+ pi.on("session_shutdown", () => { disposeFooter?.(); disposeFooter = undefined; restoreEditor(); activeCtx = undefined; });
128
285
  pi.registerCommand("path-bar", {
129
286
  description: "Configure the path bar and manage folder aliases",
130
287
  handler: async (_args, ctx) => {
131
288
  if (ctx.mode !== "tui") { ctx.ui.notify("/path-bar requires TUI mode", "error"); return; }
132
289
  load(ctx);
133
290
  install(ctx);
134
- const save = (change: (next: Config) => void) => {
135
- try { config = store.update(change); install(ctx); return true; }
291
+ const save = (change: (next: Config) => void, reinstall = true) => {
292
+ try { config = store.update(change); if (reinstall) install(ctx); return true; }
136
293
  catch (error) { ctx.ui.notify(`Could not save: ${error instanceof Error ? error.message : String(error)}`, "error"); return false; }
137
294
  };
138
- await openSettings(ctx, () => config, save);
295
+ await openSettings(ctx, () => config, save, () => footerData?.getExtensionStatuses() ?? new Map());
139
296
  },
140
297
  });
141
298
  }