@arhen/pi-senja 1.0.5 → 1.0.6

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/src/index.ts CHANGED
@@ -19,267 +19,258 @@ import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
19
19
  // ── Visual primitives ────────────────────────────────────────────────────────
20
20
 
21
21
  const GLYPH = {
22
- dot: "·",
23
- square: "▪",
24
- barFull: "█",
25
- barEmpty: "░",
26
- bracketL: "[",
27
- bracketR: "]",
28
- pipe: "|",
22
+ dot: "·",
23
+ square: "▪",
24
+ barFull: "█",
25
+ barEmpty: "░",
26
+ bracketL: "[",
27
+ bracketR: "]",
28
+ pipe: "|",
29
29
  } as const;
30
30
 
31
31
  interface RenderHandle {
32
- requestRender(): void;
32
+ requestRender(): void;
33
33
  }
34
34
 
35
35
  // ── Helpers ──────────────────────────────────────────────────────────────────
36
36
 
37
37
  /** Replace $HOME with ~, mirroring Pi's built-in footer logic. */
38
38
  function formatCwd(cwd: string): string {
39
- const home = process.env.HOME || process.env.USERPROFILE;
40
- if (!home) return cwd;
39
+ const home = process.env.HOME || process.env.USERPROFILE;
40
+ if (!home) return cwd;
41
41
 
42
- const resolvedCwd = resolve(cwd);
43
- const resolvedHome = resolve(home);
44
- const rel = relative(resolvedHome, resolvedCwd);
45
- const insideHome =
46
- rel === "" || (rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel));
42
+ const resolvedCwd = resolve(cwd);
43
+ const resolvedHome = resolve(home);
44
+ const rel = relative(resolvedHome, resolvedCwd);
45
+ const insideHome = rel === "" || (rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel));
47
46
 
48
- if (!insideHome) return cwd;
49
- return rel === "" ? "~" : `~${sep}${rel}`;
47
+ if (!insideHome) return cwd;
48
+ return rel === "" ? "~" : `~${sep}${rel}`;
50
49
  }
51
50
 
52
51
  /** Compact token formatter. */
53
52
  function fmtTokens(n: number): string {
54
- if (n < 1000) return n.toString();
55
- if (n < 10_000) return `${(n / 1000).toFixed(1)}k`;
56
- if (n < 1_000_000) return `${Math.round(n / 1000)}k`;
57
- if (n < 10_000_000) return `${(n / 1_000_000).toFixed(1)}M`;
58
- return `${Math.round(n / 1_000_000)}M`;
53
+ if (n < 1000) return n.toString();
54
+ if (n < 10_000) return `${(n / 1000).toFixed(1)}k`;
55
+ if (n < 1_000_000) return `${Math.round(n / 1000)}k`;
56
+ if (n < 10_000_000) return `${(n / 1_000_000).toFixed(1)}M`;
57
+ return `${Math.round(n / 1_000_000)}M`;
59
58
  }
60
59
 
61
60
  /** Format milliseconds as a human-readable duration. */
62
61
  function formatDuration(ms: number): string {
63
- const totalSeconds = Math.max(0, Math.floor(ms / 1000));
64
- if (totalSeconds < 60) return `${totalSeconds}s`;
62
+ const totalSeconds = Math.max(0, Math.floor(ms / 1000));
63
+ if (totalSeconds < 60) return `${totalSeconds}s`;
65
64
 
66
- const s = totalSeconds % 60;
67
- const totalMinutes = Math.floor(totalSeconds / 60);
68
- if (totalMinutes < 60) return `${totalMinutes}m ${s}s`;
65
+ const s = totalSeconds % 60;
66
+ const totalMinutes = Math.floor(totalSeconds / 60);
67
+ if (totalMinutes < 60) return `${totalMinutes}m ${s}s`;
69
68
 
70
- const m = totalMinutes % 60;
71
- const h = Math.floor(totalMinutes / 60);
72
- return `${h}h ${m}m ${s}s`;
69
+ const m = totalMinutes % 60;
70
+ const h = Math.floor(totalMinutes / 60);
71
+ return `${h}h ${m}m ${s}s`;
73
72
  }
74
73
 
75
74
  /** Right-align two text blocks, truncating left if they don't both fit. */
76
75
  function alignRight(left: string, right: string, width: number, theme: Theme): string {
77
- const rightW = visibleWidth(right);
78
- if (rightW > width) {
79
- right = truncateToWidth(right, width, theme.fg("dim", "…"));
80
- }
81
- const leftW = visibleWidth(left);
82
- const rightW2 = visibleWidth(right);
83
- const pad = width - leftW - rightW2;
84
- if (pad >= 1) {
85
- return left + " ".repeat(pad) + right;
86
- }
87
- const availableForLeft = Math.max(0, width - rightW2 - 1);
88
- const truncatedLeft = availableForLeft > 0 ? truncateToWidth(left, availableForLeft, theme.fg("dim", "…")) : "";
89
- return truncatedLeft ? truncatedLeft + " " + right : right;
76
+ const rightW = visibleWidth(right);
77
+ if (rightW > width) {
78
+ right = truncateToWidth(right, width, theme.fg("dim", "…"));
79
+ }
80
+ const leftW = visibleWidth(left);
81
+ const rightW2 = visibleWidth(right);
82
+ const pad = width - leftW - rightW2;
83
+ if (pad >= 1) {
84
+ return left + " ".repeat(pad) + right;
85
+ }
86
+ const availableForLeft = Math.max(0, width - rightW2 - 1);
87
+ const truncatedLeft = availableForLeft > 0 ? truncateToWidth(left, availableForLeft, theme.fg("dim", "…")) : "";
88
+ return truncatedLeft ? `${truncatedLeft} ${right}` : right;
90
89
  }
91
90
 
92
91
  /** Theme color for a provider name. */
93
92
  function providerColor(provider: string): ThemeColor {
94
- switch (provider.toLowerCase()) {
95
- case "anthropic":
96
- return "accent";
97
- case "openai":
98
- case "openai-codex":
99
- return "success";
100
- case "google":
101
- case "google-vertex":
102
- return "warning";
103
- case "amazon-bedrock":
104
- return "thinkingHigh";
105
- case "github-copilot":
106
- return "mdLink";
107
- case "deepseek":
108
- return "thinkingLow";
109
- case "xai":
110
- case "groq":
111
- return "error";
112
- case "opencode-go":
113
- return "accent";
114
- default:
115
- return "muted";
116
- }
93
+ switch (provider.toLowerCase()) {
94
+ case "anthropic":
95
+ return "accent";
96
+ case "openai":
97
+ case "openai-codex":
98
+ return "success";
99
+ case "google":
100
+ case "google-vertex":
101
+ return "warning";
102
+ case "amazon-bedrock":
103
+ return "thinkingHigh";
104
+ case "github-copilot":
105
+ return "mdLink";
106
+ case "deepseek":
107
+ return "thinkingLow";
108
+ case "xai":
109
+ case "groq":
110
+ return "error";
111
+ case "opencode-go":
112
+ return "accent";
113
+ default:
114
+ return "muted";
115
+ }
117
116
  }
118
117
 
119
118
  /** Theme color for an effort/thinking level. */
120
119
  function effortColor(level: ThinkingLevel | string | undefined): ThemeColor {
121
- switch (level) {
122
- case "minimal":
123
- return "thinkingMinimal";
124
- case "low":
125
- return "thinkingLow";
126
- case "medium":
127
- return "thinkingMedium";
128
- case "high":
129
- return "thinkingHigh";
130
- case "xhigh":
131
- return "thinkingXhigh";
132
- case "max":
133
- return "thinkingMax";
134
- default:
135
- return "thinkingMedium";
136
- }
120
+ switch (level) {
121
+ case "minimal":
122
+ return "thinkingMinimal";
123
+ case "low":
124
+ return "thinkingLow";
125
+ case "medium":
126
+ return "thinkingMedium";
127
+ case "high":
128
+ return "thinkingHigh";
129
+ case "xhigh":
130
+ return "thinkingXhigh";
131
+ case "max":
132
+ return "thinkingMax";
133
+ default:
134
+ return "thinkingMedium";
135
+ }
137
136
  }
138
137
 
139
138
  /** Color scale for percentage values (context usage / cache hit). */
140
139
  function stressColor(value: number, warn = 70, danger = 90): ThemeColor {
141
- if (value >= danger) return "error";
142
- if (value >= warn) return "warning";
143
- return "accent";
140
+ if (value >= danger) return "error";
141
+ if (value >= warn) return "warning";
142
+ return "accent";
144
143
  }
145
144
 
146
145
  /** Color scale for cache-hit percentage: low is red, high is green. */
147
146
  function cacheHitColor(value: number): ThemeColor {
148
- if (value < 30) return "error";
149
- if (value < 70) return "warning";
150
- return "success";
147
+ if (value < 30) return "error";
148
+ if (value < 70) return "warning";
149
+ return "success";
151
150
  }
152
151
 
153
152
  /** Render a horizontal progress bar. */
154
153
  function renderBar(theme: Theme, pct: number, barWidth: number): string {
155
- const filled = Math.max(0, Math.min(barWidth, Math.round((pct / 100) * barWidth)));
156
- const empty = barWidth - filled;
157
- const color = stressColor(pct, 70, 90);
158
-
159
- return (
160
- theme.fg("dim", GLYPH.bracketL) +
161
- theme.fg(color, GLYPH.barFull.repeat(filled)) +
162
- theme.fg("dim", GLYPH.barEmpty.repeat(empty)) +
163
- theme.fg("dim", GLYPH.bracketR)
164
- );
154
+ const filled = Math.max(0, Math.min(barWidth, Math.round((pct / 100) * barWidth)));
155
+ const empty = barWidth - filled;
156
+ const color = stressColor(pct, 70, 90);
157
+
158
+ return (
159
+ theme.fg("dim", GLYPH.bracketL) +
160
+ theme.fg(color, GLYPH.barFull.repeat(filled)) +
161
+ theme.fg("dim", GLYPH.barEmpty.repeat(empty)) +
162
+ theme.fg("dim", GLYPH.bracketR)
163
+ );
165
164
  }
166
165
 
167
166
  function sanitizeStatus(text: string): string {
168
- return text
169
- .replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\|$)/g, "")
170
- .replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, (sequence) => /^\x1b\[[0-9;:]*m$/.test(sequence) ? sequence : "")
171
- .replace(/[\r\n\t]/g, " ")
172
- .replace(/[\x00-\x08\x0b-\x1a\x1c-\x1f\x7f-\x9f]|\x1b(?!\[[0-9;:]*m)/g, "")
173
- .replace(/ +/g, " ")
174
- .trim();
167
+ return text
168
+ .replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\|$)/g, "")
169
+ .replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, (sequence) => (/^\x1b\[[0-9;:]*m$/.test(sequence) ? sequence : ""))
170
+ .replace(/[\r\n\t]/g, " ")
171
+ .replace(/[\x00-\x08\x0b-\x1a\x1c-\x1f\x7f-\x9f]|\x1b(?!\[[0-9;:]*m)/g, "")
172
+ .replace(/ +/g, " ")
173
+ .trim();
175
174
  }
176
175
 
177
176
  function renderHeader(theme: Theme, width: number): string[] {
178
- if (width <= 0) return [];
179
- const lines: string[] = [];
180
-
181
- // Column grid: 2-space indent · 8-wide eyebrow · 2-space gap · content.
182
- const INDENT = 2;
183
- const EYEBROW_W = 8;
184
- const GAP = 2;
185
- const contentStart = INDENT + EYEBROW_W + GAP;
186
- const contentWidth = Math.max(0, width - contentStart);
187
-
188
- // A keybinding pair: the key glows in accent, the verb sits quiet in dim.
189
- const pair = (key: string, desc: string) =>
190
- `${theme.fg("accent", key)} ${theme.fg("dim", desc)}`;
191
- const sep = theme.fg("dim", " · ");
192
- const ellipsis = theme.fg("dim", "…");
193
-
194
- // Greedy flow: pack pairs into the content column, wrapping under the
195
- // eyebrow when a line would overflow. Continuation lines align with the
196
- // first content column so the key map reads as a tidy block.
197
- const flowGroup = (label: string, pairs: string[]): string[] => {
198
- const out: string[] = [];
199
- const prefix =
200
- " ".repeat(INDENT) +
201
- theme.fg("warning", label) +
202
- " ".repeat(Math.max(1, EYEBROW_W - visibleWidth(label))) +
203
- " ".repeat(GAP);
204
- let line = prefix;
205
- let lineW = contentStart;
206
-
207
- for (const seg of pairs) {
208
- const segW = visibleWidth(seg);
209
- if (lineW === contentStart) {
210
- const fit = segW <= contentWidth ? seg : truncateToWidth(seg, contentWidth, ellipsis);
211
- line += fit;
212
- lineW += visibleWidth(fit);
213
- } else if (lineW + visibleWidth(sep) + segW <= width) {
214
- line += sep + seg;
215
- lineW += visibleWidth(sep) + segW;
216
- } else {
217
- out.push(line);
218
- const fit = segW <= contentWidth ? seg : truncateToWidth(seg, contentWidth, ellipsis);
219
- line = " ".repeat(contentStart) + fit;
220
- lineW = contentStart + visibleWidth(fit);
221
- }
222
- }
223
- out.push(line);
224
- return out;
225
- };
226
-
227
- // --- Identity line: bold accent "pi", muted version, no leading spacing ---
228
- lines.push(theme.bold(theme.fg("accent", "pi")) + " " + theme.fg("muted", `v${VERSION}`));
229
- lines.push("");
230
-
231
- // --- Key map, grouped by intent ---
232
- lines.push(
233
- ...flowGroup("control", [
234
- pair("esc", "interrupt"),
235
- pair("ctrl+c", "clear"),
236
- pair("ctrl+d", "exit"),
237
- pair("ctrl+z", "suspend"),
238
- pair("ctrl+k", "delete to end"),
239
- ]),
240
- ...flowGroup("models", [
241
- pair("ctrl+p", "next"),
242
- pair("shift+ctrl+p", "prev"),
243
- pair("ctrl+l", "select"),
244
- pair("shift+tab", "thinking"),
245
- ]),
246
- ...flowGroup("view", [
247
- pair("ctrl+o", "tools"),
248
- pair("ctrl+t", "thinking"),
249
- pair("ctrl+g", "editor"),
250
- ]),
251
- ...flowGroup("input", [
252
- pair("/", "commands"),
253
- pair("!", "bash"),
254
- pair("!!", "bash·nc"),
255
- pair("alt+enter", "follow-up"),
256
- pair("alt+up", "queue"),
257
- pair("ctrl+v", "image"),
258
- pair("drop", "attach files"),
259
- ]),
260
- );
261
-
262
- // --- Hint ---
263
- lines.push("");
264
- lines.push(
265
- " ".repeat(INDENT) +
266
- theme.fg("muted", "Pi can explain its own features and look up its docs."),
267
- );
268
-
269
- return lines.map((line) => truncateToWidth(line, width, ellipsis));
177
+ if (width <= 0) return [];
178
+ const lines: string[] = [];
179
+
180
+ // Column grid: 2-space indent · 8-wide eyebrow · 2-space gap · content.
181
+ const INDENT = 2;
182
+ const EYEBROW_W = 8;
183
+ const GAP = 2;
184
+ const contentStart = INDENT + EYEBROW_W + GAP;
185
+ const contentWidth = Math.max(0, width - contentStart);
186
+
187
+ // A keybinding pair: the key glows in accent, the verb sits quiet in dim.
188
+ const pair = (key: string, desc: string) => `${theme.fg("accent", key)} ${theme.fg("dim", desc)}`;
189
+ const sep = theme.fg("dim", " · ");
190
+ const ellipsis = theme.fg("dim", "…");
191
+
192
+ // Greedy flow: pack pairs into the content column, wrapping under the
193
+ // eyebrow when a line would overflow. Continuation lines align with the
194
+ // first content column so the key map reads as a tidy block.
195
+ const flowGroup = (label: string, pairs: string[]): string[] => {
196
+ const out: string[] = [];
197
+ const prefix =
198
+ " ".repeat(INDENT) +
199
+ theme.fg("warning", label) +
200
+ " ".repeat(Math.max(1, EYEBROW_W - visibleWidth(label))) +
201
+ " ".repeat(GAP);
202
+ let line = prefix;
203
+ let lineW = contentStart;
204
+
205
+ for (const seg of pairs) {
206
+ const segW = visibleWidth(seg);
207
+ if (lineW === contentStart) {
208
+ const fit = segW <= contentWidth ? seg : truncateToWidth(seg, contentWidth, ellipsis);
209
+ line += fit;
210
+ lineW += visibleWidth(fit);
211
+ } else if (lineW + visibleWidth(sep) + segW <= width) {
212
+ line += sep + seg;
213
+ lineW += visibleWidth(sep) + segW;
214
+ } else {
215
+ out.push(line);
216
+ const fit = segW <= contentWidth ? seg : truncateToWidth(seg, contentWidth, ellipsis);
217
+ line = " ".repeat(contentStart) + fit;
218
+ lineW = contentStart + visibleWidth(fit);
219
+ }
220
+ }
221
+ out.push(line);
222
+ return out;
223
+ };
224
+
225
+ // --- Identity line: bold accent "pi", muted version, no leading spacing ---
226
+ lines.push(`${theme.bold(theme.fg("accent", "pi"))} ${theme.fg("muted", `v${VERSION}`)}`);
227
+ lines.push("");
228
+
229
+ // --- Key map, grouped by intent ---
230
+ lines.push(
231
+ ...flowGroup("control", [
232
+ pair("esc", "interrupt"),
233
+ pair("ctrl+c", "clear"),
234
+ pair("ctrl+d", "exit"),
235
+ pair("ctrl+z", "suspend"),
236
+ pair("ctrl+k", "delete to end"),
237
+ ]),
238
+ ...flowGroup("models", [
239
+ pair("ctrl+p", "next"),
240
+ pair("shift+ctrl+p", "prev"),
241
+ pair("ctrl+l", "select"),
242
+ pair("shift+tab", "thinking"),
243
+ ]),
244
+ ...flowGroup("view", [pair("ctrl+o", "tools"), pair("ctrl+t", "thinking"), pair("ctrl+g", "editor")]),
245
+ ...flowGroup("input", [
246
+ pair("/", "commands"),
247
+ pair("!", "bash"),
248
+ pair("!!", "bash·nc"),
249
+ pair("alt+enter", "follow-up"),
250
+ pair("alt+up", "queue"),
251
+ pair("ctrl+v", "image"),
252
+ pair("drop", "attach files"),
253
+ ]),
254
+ );
255
+
256
+ // --- Hint ---
257
+ lines.push("");
258
+ lines.push(" ".repeat(INDENT) + theme.fg("muted", "Pi can explain its own features and look up its docs."));
259
+
260
+ return lines.map((line) => truncateToWidth(line, width, ellipsis));
270
261
  }
271
262
 
272
263
  function applyHeader(ctx: ExtensionContext): void {
273
- ctx.ui.setHeader((_tui, theme) => ({
274
- render(width: number): string[] {
275
- return renderHeader(theme, width);
276
- },
277
- invalidate() {},
278
- }));
264
+ ctx.ui.setHeader((_tui, theme) => ({
265
+ render(width: number): string[] {
266
+ return renderHeader(theme, width);
267
+ },
268
+ invalidate() {},
269
+ }));
279
270
  }
280
271
 
281
272
  function restoreHeader(ctx: ExtensionContext): void {
282
- ctx.ui.setHeader(undefined);
273
+ ctx.ui.setHeader(undefined);
283
274
  }
284
275
 
285
276
  /** Clear the visible screen and home the cursor on initial launch.
@@ -289,313 +280,308 @@ function restoreHeader(ctx: ExtensionContext): void {
289
280
  * Scrollback is preserved.
290
281
  */
291
282
  function clearVisibleScreenOnStartup(): void {
292
- if (process.stdout.isTTY) {
293
- process.stdout.write("\x1b[2J\x1b[H");
294
- }
283
+ if (process.stdout.isTTY) {
284
+ process.stdout.write("\x1b[2J\x1b[H");
285
+ }
295
286
  }
296
287
 
297
288
  // ── Extension ────────────────────────────────────────────────────────────────
298
289
 
299
290
  export default function (pi: ExtensionAPI) {
300
- let renderHandle: RenderHandle | undefined;
301
- let disposeFooter: (() => void) | undefined;
302
- let enabled = true;
303
- let workingSince: number | undefined;
304
- let workingTimer: ReturnType<typeof setInterval> | undefined;
305
- let lastDoneIn: number | undefined;
306
- let modeWorkingMessage: string | undefined;
307
-
308
- const unsubscribeMode = pi.events.on("pi-mode:working-message", (message) => {
309
- if (message === undefined || typeof message === "string") modeWorkingMessage = message || undefined;
310
- });
311
-
312
- function requestFooterRender(): void {
313
- renderHandle?.requestRender();
314
- }
315
-
316
- function clearWorkingTimers(): void {
317
- if (workingTimer !== undefined) {
318
- clearInterval(workingTimer);
319
- workingTimer = undefined;
320
- }
321
- }
322
-
323
- // Re-render when state that the footer displays changes.
324
- pi.on("thinking_level_select", requestFooterRender);
325
- pi.on("model_select", requestFooterRender);
326
-
327
- // Track how long the current prompt has been running.
328
- pi.on("agent_start", (_event, ctx) => {
329
- clearWorkingTimers();
330
- workingSince = Date.now();
331
- lastDoneIn = undefined;
332
-
333
- if (ctx.mode !== "tui") return;
334
-
335
- const tick = () => {
336
- if (workingSince === undefined) return;
337
- const elapsed = formatDuration(Date.now() - workingSince);
338
- try {
339
- ctx.ui.setWorkingMessage(`${modeWorkingMessage ?? "Working…"} ${elapsed}`);
340
- } catch {
341
- // Ignore if the UI is already torn down.
342
- }
343
- requestFooterRender();
344
- };
345
-
346
- tick();
347
- workingTimer = setInterval(tick, 250);
348
- });
349
-
350
- // Report final duration and clean up timers.
351
- pi.on("agent_end", (_event, ctx) => {
352
- clearWorkingTimers();
353
-
354
- if (workingSince !== undefined) {
355
- lastDoneIn = Date.now() - workingSince;
356
- workingSince = undefined;
357
- }
358
-
359
- requestFooterRender();
360
-
361
- // Show a notification and working message with the total elapsed time.
362
- // The working message area may be hidden after streaming ends, so we
363
- // make it visible first. The footer also displays this until the next task.
364
- if (lastDoneIn !== undefined && ctx.mode === "tui") {
365
- try {
366
- ctx.ui.setWorkingVisible(true);
367
- ctx.ui.setWorkingMessage(`Worked for ${formatDuration(lastDoneIn)}`);
368
- ctx.ui.notify(`Worked for ${formatDuration(lastDoneIn)}`, "info");
369
- } catch {
370
- // Ignore if the UI is already torn down.
371
- }
372
- }
373
- });
374
-
375
- function applyFooter(ctx: ExtensionContext): void {
376
- disposeFooter?.();
377
- ctx.ui.setFooter((tui, theme, footerData) => {
378
- disposeFooter?.();
379
- renderHandle = tui;
380
- const unsubscribeBranch = footerData.onBranchChange(() => tui.requestRender());
381
- let disposed = false;
382
- const dispose = () => {
383
- if (disposed) return;
384
- disposed = true;
385
- unsubscribeBranch();
386
- if (disposeFooter === dispose) {
387
- disposeFooter = undefined;
388
- renderHandle = undefined;
389
- }
390
- };
391
- disposeFooter = dispose;
392
-
393
- return {
394
- dispose,
395
- invalidate() {
396
- // Stateless render; nothing to cache.
397
- },
398
- render(width: number): string[] {
399
- if (width <= 0) return [];
400
- // ── Aggregate usage across every assistant message ───────────────
401
- let totalInput = 0;
402
- let totalOutput = 0;
403
- let totalCacheRead = 0;
404
- let totalCacheWrite = 0;
405
- let totalCost = 0;
406
- let latestCacheHitRate: number | undefined;
407
-
408
- for (const entry of ctx.sessionManager.getEntries()) {
409
- if (entry.type === "message" && entry.message.role === "assistant") {
410
- const m = entry.message as AssistantMessage;
411
- totalInput += m.usage.input;
412
- totalOutput += m.usage.output;
413
- totalCacheRead += m.usage.cacheRead;
414
- totalCacheWrite += m.usage.cacheWrite;
415
- totalCost += m.usage.cost.total;
416
-
417
- const promptTokens = m.usage.input + m.usage.cacheRead + m.usage.cacheWrite;
418
- latestCacheHitRate =
419
- promptTokens > 0 ? (m.usage.cacheRead / promptTokens) * 100 : undefined;
420
- }
421
- }
422
-
423
- // ── Context usage for the active model ───────────────────────────
424
- const contextUsage = ctx.getContextUsage();
425
- const contextWindow = contextUsage?.contextWindow ?? ctx.model?.contextWindow ?? 0;
426
- const contextTokens = contextUsage?.tokens ?? null;
427
- const contextPercent = contextUsage?.percent ?? null;
428
- const contextPctValue = contextPercent ?? 0;
429
-
430
- // ── Location / session metadata ──────────────────────────────────
431
- const cwd = sanitizeStatus(formatCwd(ctx.sessionManager.getCwd()));
432
- const branch = sanitizeStatus(footerData.getGitBranch() ?? "");
433
- const sessionName = sanitizeStatus(ctx.sessionManager.getSessionName() ?? "");
434
-
435
- // ── Provider / model / effort metadata ───────────────────────────
436
- const provider = sanitizeStatus(ctx.model?.provider ?? "none");
437
- const modelId = sanitizeStatus(ctx.model?.id ?? "no-model");
438
- const reasoning = ctx.model?.reasoning ?? false;
439
- const usingSubscription = ctx.model ? ctx.modelRegistry.isUsingOAuth(ctx.model) : false;
440
-
441
- // ── Line 1: location left, provider ▪ model ▪ effort right ───────
442
- let locationBlock = theme.fg("accent", cwd);
443
- if (branch) {
444
- locationBlock += ` ${theme.fg("dim", "branch")} ${theme.fg("success", branch)}`;
445
- }
446
- if (sessionName) {
447
- locationBlock += ` ${theme.fg("dim", "session")} ${theme.fg("text", sessionName)}`;
448
- }
449
-
450
- let modelBlock = `${theme.fg(providerColor(provider), String(provider))} ${theme.fg("dim", GLYPH.square)} ${theme.fg("text", modelId)}`;
451
- if (reasoning) {
452
- const level = pi.getThinkingLevel();
453
- modelBlock += ` ${theme.fg("dim", GLYPH.square)} ${theme.fg(effortColor(level), level)}`;
454
- }
455
-
456
- const line1 = alignRight(locationBlock, modelBlock, width, theme);
457
-
458
- // ── Line 2: working/done timer + stats left, context right ───────
459
- const stats: string[] = [];
460
-
461
- if (totalInput > 0) {
462
- stats.push(`${theme.fg("dim", "in")} ${theme.fg("accent", `↑${fmtTokens(totalInput)}`)}`);
463
- }
464
- if (totalOutput > 0) {
465
- stats.push(`${theme.fg("dim", "out")} ${theme.fg("success", `↓${fmtTokens(totalOutput)}`)}`);
466
- }
467
- if (latestCacheHitRate !== undefined) {
468
- stats.push(
469
- `${theme.fg("dim", "cache hit")} ${theme.fg(
470
- cacheHitColor(latestCacheHitRate),
471
- `${latestCacheHitRate.toFixed(1)}%`,
472
- )}`,
473
- );
474
- }
475
-
476
- if (totalCost > 0) {
477
- const costText = `$${totalCost.toFixed(3)}${usingSubscription ? " (sub)" : ""}`;
478
- stats.push(`${theme.fg("dim", "cost")} ${theme.fg("warning", costText)}`);
479
- }
480
-
481
- const statsBlock = stats.join(` ${theme.fg("dim", GLYPH.pipe)} `);
482
-
483
- let contextBlock = "";
484
- if (contextTokens !== null && contextTokens > 0) {
485
- const pctText = theme.fg(stressColor(contextPctValue, 70, 90), `${contextPctValue.toFixed(1)}%`);
486
- const contextText = `${theme.fg("text", fmtTokens(contextTokens))}${theme.fg("dim", "/")}${theme.fg("text", fmtTokens(contextWindow))}`;
487
- // Fit the context block within the available width so the right-hand
488
- // numbers aren't truncated (e.g. 50k/500k becoming 50k/5...).
489
- const reserved = visibleWidth(pctText) + visibleWidth(contextText) + 4 + 2; // separators + brackets
490
- const barWidth = Math.max(6, Math.min(16, width - reserved));
491
- contextBlock = `${renderBar(theme, contextPctValue, barWidth)} ${pctText} ${theme.fg("dim", GLYPH.square)} ${contextText}`;
492
- }
493
-
494
- let timerBlock = "";
495
- if (workingSince !== undefined) {
496
- timerBlock = `${theme.fg("dim", "working")} ${theme.fg("accent", formatDuration(Date.now() - workingSince))}`;
497
- } else if (lastDoneIn !== undefined) {
498
- timerBlock = `${theme.fg("success", "worked")} ${theme.fg("text", `for ${formatDuration(lastDoneIn)}`)}`;
499
- }
500
-
501
- let rightBlock = statsBlock;
502
- if (contextBlock) {
503
- rightBlock = rightBlock ? alignRight(rightBlock, contextBlock, width, theme) : contextBlock;
504
- }
505
-
506
- let line2: string | undefined;
507
- if (timerBlock && rightBlock) {
508
- line2 = alignRight(timerBlock, rightBlock, width, theme);
509
- } else if (timerBlock) {
510
- line2 = timerBlock;
511
- } else if (rightBlock) {
512
- line2 = rightBlock;
513
- }
514
-
515
- // ── Optional line 3: raw extension statuses ──────────────────────
516
- const lines: string[] = [line1];
517
- if (line2) {
518
- lines.push(line2);
519
- }
520
- const extensionStatuses = footerData.getExtensionStatuses();
521
-
522
- if (extensionStatuses.size > 0) {
523
- const divider = ` ${GLYPH.pipe} `;
524
- const rawStatuses = Array.from(extensionStatuses.entries())
525
- .sort(([a], [b]) => a.localeCompare(b))
526
- .map(([, text]) => sanitizeStatus(text))
527
- .filter((text) => text.length > 0)
528
- .join(divider);
529
- if (rawStatuses) {
530
- lines.push(theme.fg("dim", rawStatuses));
531
- }
532
- }
533
-
534
- // Truncate every line to exact terminal width; no trailing spacing.
535
- return lines.map((line) => truncateToWidth(line, width, theme.fg("dim", "…")));
536
- },
537
- };
538
- });
539
- }
540
-
541
- function restoreFooter(ctx: ExtensionContext): void {
542
- disposeFooter?.();
543
- ctx.ui.setFooter(undefined);
544
- }
545
-
546
- // Toggle command.
547
- pi.registerCommand("senja", {
548
- description: "Toggle the Senja header and footer",
549
- handler: async (_args, ctx) => {
550
- if (ctx.mode !== "tui") {
551
- if (ctx.hasUI) ctx.ui.notify("Senja requires terminal UI mode", "info");
552
- return;
553
- }
554
- enabled = !enabled;
555
- if (enabled) {
556
- applyFooter(ctx);
557
- applyHeader(ctx);
558
- ctx.ui.notify("Senja enabled", "info");
559
- } else {
560
- restoreFooter(ctx);
561
- restoreHeader(ctx);
562
- ctx.ui.notify("Default UI restored", "info");
563
- }
564
- },
565
- });
566
-
567
- pi.on("session_start", (event, ctx) => {
568
- clearWorkingTimers();
569
- workingSince = undefined;
570
- lastDoneIn = undefined;
571
- disposeFooter?.();
572
- if (ctx.mode !== "tui") return;
573
-
574
- if (event.reason === "startup") {
575
- clearVisibleScreenOnStartup();
576
- }
577
-
578
- const result = ctx.ui.setTheme("senja");
579
- if (!result.success) {
580
- ctx.ui.notify(`Senja theme: ${result.error ?? "unknown error"}`, "warning");
581
- }
582
-
583
- if (enabled) {
584
- applyFooter(ctx);
585
- applyHeader(ctx);
586
- } else {
587
- restoreFooter(ctx);
588
- restoreHeader(ctx);
589
- }
590
- });
591
-
592
- pi.on("session_shutdown", () => {
593
- unsubscribeMode();
594
- modeWorkingMessage = undefined;
595
- clearWorkingTimers();
596
- workingSince = undefined;
597
- lastDoneIn = undefined;
598
- disposeFooter?.();
599
- renderHandle = undefined;
600
- });
291
+ let renderHandle: RenderHandle | undefined;
292
+ let disposeFooter: (() => void) | undefined;
293
+ let enabled = true;
294
+ let workingSince: number | undefined;
295
+ let workingTimer: ReturnType<typeof setInterval> | undefined;
296
+ let lastDoneIn: number | undefined;
297
+ let modeWorkingMessage: string | undefined;
298
+
299
+ const unsubscribeMode = pi.events.on("pi-mode:working-message", (message) => {
300
+ if (message === undefined || typeof message === "string") modeWorkingMessage = message || undefined;
301
+ });
302
+
303
+ function requestFooterRender(): void {
304
+ renderHandle?.requestRender();
305
+ }
306
+
307
+ function clearWorkingTimers(): void {
308
+ if (workingTimer !== undefined) {
309
+ clearInterval(workingTimer);
310
+ workingTimer = undefined;
311
+ }
312
+ }
313
+
314
+ // Re-render when state that the footer displays changes.
315
+ pi.on("thinking_level_select", requestFooterRender);
316
+ pi.on("model_select", requestFooterRender);
317
+
318
+ // Track how long the current prompt has been running.
319
+ pi.on("agent_start", (_event, ctx) => {
320
+ clearWorkingTimers();
321
+ workingSince = Date.now();
322
+ lastDoneIn = undefined;
323
+
324
+ if (ctx.mode !== "tui") return;
325
+
326
+ const tick = () => {
327
+ if (workingSince === undefined) return;
328
+ const elapsed = formatDuration(Date.now() - workingSince);
329
+ try {
330
+ ctx.ui.setWorkingMessage(`${modeWorkingMessage ?? "Working…"} ${elapsed}`);
331
+ } catch {
332
+ // Ignore if the UI is already torn down.
333
+ }
334
+ requestFooterRender();
335
+ };
336
+
337
+ tick();
338
+ workingTimer = setInterval(tick, 250);
339
+ });
340
+
341
+ // Report final duration and clean up timers.
342
+ pi.on("agent_end", (_event, ctx) => {
343
+ clearWorkingTimers();
344
+
345
+ if (workingSince !== undefined) {
346
+ lastDoneIn = Date.now() - workingSince;
347
+ workingSince = undefined;
348
+ }
349
+
350
+ requestFooterRender();
351
+
352
+ // Show a notification and working message with the total elapsed time.
353
+ // The working message area may be hidden after streaming ends, so we
354
+ // make it visible first. The footer also displays this until the next task.
355
+ if (lastDoneIn !== undefined && ctx.mode === "tui") {
356
+ try {
357
+ ctx.ui.setWorkingVisible(true);
358
+ ctx.ui.setWorkingMessage(`Worked for ${formatDuration(lastDoneIn)}`);
359
+ ctx.ui.notify(`Worked for ${formatDuration(lastDoneIn)}`, "info");
360
+ } catch {
361
+ // Ignore if the UI is already torn down.
362
+ }
363
+ }
364
+ });
365
+
366
+ function applyFooter(ctx: ExtensionContext): void {
367
+ disposeFooter?.();
368
+ ctx.ui.setFooter((tui, theme, footerData) => {
369
+ disposeFooter?.();
370
+ renderHandle = tui;
371
+ const unsubscribeBranch = footerData.onBranchChange(() => tui.requestRender());
372
+ let disposed = false;
373
+ const dispose = () => {
374
+ if (disposed) return;
375
+ disposed = true;
376
+ unsubscribeBranch();
377
+ if (disposeFooter === dispose) {
378
+ disposeFooter = undefined;
379
+ renderHandle = undefined;
380
+ }
381
+ };
382
+ disposeFooter = dispose;
383
+
384
+ return {
385
+ dispose,
386
+ invalidate() {
387
+ // Stateless render; nothing to cache.
388
+ },
389
+ render(width: number): string[] {
390
+ if (width <= 0) return [];
391
+ // ── Aggregate usage across every assistant message ───────────────
392
+ let totalInput = 0;
393
+ let totalOutput = 0;
394
+ let totalCost = 0;
395
+ let latestCacheHitRate: number | undefined;
396
+
397
+ for (const entry of ctx.sessionManager.getEntries()) {
398
+ if (entry.type === "message" && entry.message.role === "assistant") {
399
+ const m = entry.message as AssistantMessage;
400
+ totalInput += m.usage.input;
401
+ totalOutput += m.usage.output;
402
+ totalCost += m.usage.cost.total;
403
+
404
+ const promptTokens = m.usage.input + m.usage.cacheRead + m.usage.cacheWrite;
405
+ latestCacheHitRate = promptTokens > 0 ? (m.usage.cacheRead / promptTokens) * 100 : undefined;
406
+ }
407
+ }
408
+
409
+ // ── Context usage for the active model ───────────────────────────
410
+ const contextUsage = ctx.getContextUsage();
411
+ const contextWindow = contextUsage?.contextWindow ?? ctx.model?.contextWindow ?? 0;
412
+ const contextTokens = contextUsage?.tokens ?? null;
413
+ const contextPercent = contextUsage?.percent ?? null;
414
+ const contextPctValue = contextPercent ?? 0;
415
+
416
+ // ── Location / session metadata ──────────────────────────────────
417
+ const cwd = sanitizeStatus(formatCwd(ctx.sessionManager.getCwd()));
418
+ const branch = sanitizeStatus(footerData.getGitBranch() ?? "");
419
+ const sessionName = sanitizeStatus(ctx.sessionManager.getSessionName() ?? "");
420
+
421
+ // ── Provider / model / effort metadata ───────────────────────────
422
+ const provider = sanitizeStatus(ctx.model?.provider ?? "none");
423
+ const modelId = sanitizeStatus(ctx.model?.id ?? "no-model");
424
+ const reasoning = ctx.model?.reasoning ?? false;
425
+ const usingSubscription = ctx.model ? ctx.modelRegistry.isUsingOAuth(ctx.model) : false;
426
+
427
+ // ── Line 1: location left, provider ▪ model ▪ effort right ───────
428
+ let locationBlock = theme.fg("accent", cwd);
429
+ if (branch) {
430
+ locationBlock += ` ${theme.fg("dim", "branch")} ${theme.fg("success", branch)}`;
431
+ }
432
+ if (sessionName) {
433
+ locationBlock += ` ${theme.fg("dim", "session")} ${theme.fg("text", sessionName)}`;
434
+ }
435
+
436
+ let modelBlock = `${theme.fg(providerColor(provider), String(provider))} ${theme.fg("dim", GLYPH.square)} ${theme.fg("text", modelId)}`;
437
+ if (reasoning) {
438
+ const level = pi.getThinkingLevel();
439
+ modelBlock += ` ${theme.fg("dim", GLYPH.square)} ${theme.fg(effortColor(level), level)}`;
440
+ }
441
+
442
+ const line1 = alignRight(locationBlock, modelBlock, width, theme);
443
+
444
+ // ── Line 2: working/done timer + stats left, context right ───────
445
+ const stats: string[] = [];
446
+
447
+ if (totalInput > 0) {
448
+ stats.push(`${theme.fg("dim", "in")} ${theme.fg("accent", `↑${fmtTokens(totalInput)}`)}`);
449
+ }
450
+ if (totalOutput > 0) {
451
+ stats.push(`${theme.fg("dim", "out")} ${theme.fg("success", `↓${fmtTokens(totalOutput)}`)}`);
452
+ }
453
+ if (latestCacheHitRate !== undefined) {
454
+ stats.push(
455
+ `${theme.fg("dim", "cache hit")} ${theme.fg(
456
+ cacheHitColor(latestCacheHitRate),
457
+ `${latestCacheHitRate.toFixed(1)}%`,
458
+ )}`,
459
+ );
460
+ }
461
+
462
+ if (totalCost > 0) {
463
+ const costText = `$${totalCost.toFixed(3)}${usingSubscription ? " (sub)" : ""}`;
464
+ stats.push(`${theme.fg("dim", "cost")} ${theme.fg("warning", costText)}`);
465
+ }
466
+
467
+ const statsBlock = stats.join(` ${theme.fg("dim", GLYPH.pipe)} `);
468
+
469
+ let contextBlock = "";
470
+ if (contextTokens !== null && contextTokens > 0) {
471
+ const pctText = theme.fg(stressColor(contextPctValue, 70, 90), `${contextPctValue.toFixed(1)}%`);
472
+ const contextText = `${theme.fg("text", fmtTokens(contextTokens))}${theme.fg("dim", "/")}${theme.fg("text", fmtTokens(contextWindow))}`;
473
+ // Fit the context block within the available width so the right-hand
474
+ // numbers aren't truncated (e.g. 50k/500k becoming 50k/5...).
475
+ const reserved = visibleWidth(pctText) + visibleWidth(contextText) + 4 + 2; // separators + brackets
476
+ const barWidth = Math.max(6, Math.min(16, width - reserved));
477
+ contextBlock = `${renderBar(theme, contextPctValue, barWidth)} ${pctText} ${theme.fg("dim", GLYPH.square)} ${contextText}`;
478
+ }
479
+
480
+ let timerBlock = "";
481
+ if (workingSince !== undefined) {
482
+ timerBlock = `${theme.fg("dim", "working")} ${theme.fg("accent", formatDuration(Date.now() - workingSince))}`;
483
+ } else if (lastDoneIn !== undefined) {
484
+ timerBlock = `${theme.fg("success", "worked")} ${theme.fg("text", `for ${formatDuration(lastDoneIn)}`)}`;
485
+ }
486
+
487
+ let rightBlock = statsBlock;
488
+ if (contextBlock) {
489
+ rightBlock = rightBlock ? alignRight(rightBlock, contextBlock, width, theme) : contextBlock;
490
+ }
491
+
492
+ let line2: string | undefined;
493
+ if (timerBlock && rightBlock) {
494
+ line2 = alignRight(timerBlock, rightBlock, width, theme);
495
+ } else if (timerBlock) {
496
+ line2 = timerBlock;
497
+ } else if (rightBlock) {
498
+ line2 = rightBlock;
499
+ }
500
+
501
+ // ── Optional line 3: raw extension statuses ──────────────────────
502
+ const lines: string[] = [line1];
503
+ if (line2) {
504
+ lines.push(line2);
505
+ }
506
+ const extensionStatuses = footerData.getExtensionStatuses();
507
+
508
+ if (extensionStatuses.size > 0) {
509
+ const divider = ` ${GLYPH.pipe} `;
510
+ const rawStatuses = Array.from(extensionStatuses.entries())
511
+ .sort(([a], [b]) => a.localeCompare(b))
512
+ .map(([, text]) => sanitizeStatus(text))
513
+ .filter((text) => text.length > 0)
514
+ .join(divider);
515
+ if (rawStatuses) {
516
+ lines.push(theme.fg("dim", rawStatuses));
517
+ }
518
+ }
519
+
520
+ // Truncate every line to exact terminal width; no trailing spacing.
521
+ return lines.map((line) => truncateToWidth(line, width, theme.fg("dim", "…")));
522
+ },
523
+ };
524
+ });
525
+ }
526
+
527
+ function restoreFooter(ctx: ExtensionContext): void {
528
+ disposeFooter?.();
529
+ ctx.ui.setFooter(undefined);
530
+ }
531
+
532
+ // Toggle command.
533
+ pi.registerCommand("senja", {
534
+ description: "Toggle the Senja header and footer",
535
+ handler: async (_args, ctx) => {
536
+ if (ctx.mode !== "tui") {
537
+ if (ctx.hasUI) ctx.ui.notify("Senja requires terminal UI mode", "info");
538
+ return;
539
+ }
540
+ enabled = !enabled;
541
+ if (enabled) {
542
+ applyFooter(ctx);
543
+ applyHeader(ctx);
544
+ ctx.ui.notify("Senja enabled", "info");
545
+ } else {
546
+ restoreFooter(ctx);
547
+ restoreHeader(ctx);
548
+ ctx.ui.notify("Default UI restored", "info");
549
+ }
550
+ },
551
+ });
552
+
553
+ pi.on("session_start", (event, ctx) => {
554
+ clearWorkingTimers();
555
+ workingSince = undefined;
556
+ lastDoneIn = undefined;
557
+ disposeFooter?.();
558
+ if (ctx.mode !== "tui") return;
559
+
560
+ if (event.reason === "startup") {
561
+ clearVisibleScreenOnStartup();
562
+ }
563
+
564
+ const result = ctx.ui.setTheme("senja");
565
+ if (!result.success) {
566
+ ctx.ui.notify(`Senja theme: ${result.error ?? "unknown error"}`, "warning");
567
+ }
568
+
569
+ if (enabled) {
570
+ applyFooter(ctx);
571
+ applyHeader(ctx);
572
+ } else {
573
+ restoreFooter(ctx);
574
+ restoreHeader(ctx);
575
+ }
576
+ });
577
+
578
+ pi.on("session_shutdown", () => {
579
+ unsubscribeMode();
580
+ modeWorkingMessage = undefined;
581
+ clearWorkingTimers();
582
+ workingSince = undefined;
583
+ lastDoneIn = undefined;
584
+ disposeFooter?.();
585
+ renderHandle = undefined;
586
+ });
601
587
  }