@arhen/pi-senja 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,45 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 nocte
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
23
+ Gruvbox Material palette
24
+
25
+ MIT License
26
+
27
+ Copyright (c) 2020 sainnhe
28
+
29
+ Permission is hereby granted, free of charge, to any person obtaining a copy
30
+ of this software and associated documentation files (the "Software"), to deal
31
+ in the Software without restriction, including without limitation the rights
32
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
33
+ copies of the Software, and to permit persons to whom the Software is
34
+ furnished to do so, subject to the following conditions:
35
+
36
+ The above copyright notice and this permission notice shall be included in all
37
+ copies or substantial portions of the Software.
38
+
39
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
40
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
41
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
42
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
43
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
44
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
45
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,43 @@
1
- # Temporary Holding Version
1
+ # @arhen/pi-senja
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Senja theme and Haiku's tidier header and footer for [Pi](https://pi.dev).
4
+
5
+ Forked from [pi-haiku](https://github.com/nnocte/pi-haiku) **0.2.0** by **nocte**, under MIT. The header/footer layout and behavior are preserved; branding, palette, and Pi 1.0 compatibility/safety fixes are the changes. Palette from [Gruvbox Material](https://github.com/sainnhe/gruvbox-material) by **sainnhe**, also MIT.
6
+
7
+ ## What's in it
8
+
9
+ - **Gruvbox Material dark/medium/material** — exact colors captured from Neovim, matching the Ghostty Senja theme. Background `#282828`, foreground `#d4be98`, orange accent `#e78a4e`. All 56 Pi roles and HTML export backgrounds use palette variables.
10
+ - **A header** with shortcuts grouped by control, models, view, and input.
11
+ - **A footer** with location, Git branch, session name, provider, model, thinking effort (including `max`), context bar, token usage, latest cache-hit rate, cost, OAuth subscription marker, and extension statuses.
12
+ - **A live timer** while Pi works, plus elapsed-time completion message and notification.
13
+ - **A fresh start** — clear the visible screen on initial terminal startup without clearing scrollback.
14
+
15
+ Enabled by default in terminal UI mode. Print, JSON, SDK, and RPC modes do not install terminal components, switch themes, clear the screen, or start UI timers. `/senja` in RPC mode reports that terminal UI is required.
16
+
17
+ ## Install
18
+
19
+ ```bash
20
+ pi install npm:@arhen/pi-senja
21
+ ```
22
+
23
+ Disable/remove `pi-haiku` or other header/footer replacements to avoid competing UI ownership.
24
+
25
+ ## Toggle
26
+
27
+ Type `/senja` to turn the header and footer on or off. The theme stays selected. Terminal session startup selects `senja`; selecting another theme afterward still works.
28
+
29
+ ## Development
30
+
31
+ From the monorepo root, with development dependencies available:
32
+
33
+ ```bash
34
+ bun test packages/add/pi-senja/test
35
+ bunx tsc -p packages/add/pi-senja/tsconfig.json --noEmit
36
+ npm pack --dry-run --workspace @arhen/pi-senja
37
+ ```
38
+
39
+ Tests use fake UI/session/timer handles, real Pi width utilities, and the current host theme loader when available. They do not open terminals or write user settings. Set `SENJA_PI_HOST` to an installed Pi coding-agent package directory to validate its theme schema and loader (for example, a Pi 1.0 installation).
40
+
41
+ ## License
42
+
43
+ MIT. Original **2026 nocte** and Gruvbox Material **2020 sainnhe** notices retained in [LICENSE](LICENSE).
package/package.json CHANGED
@@ -1,6 +1,48 @@
1
1
  {
2
2
  "name": "@arhen/pi-senja",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "Senja Gruvbox Material theme with Haiku's structured header, footer, and live timer for Pi.",
5
+ "license": "MIT",
6
+ "author": "arhen",
7
+ "contributors": ["nocte <nocte19@gmail.com>"],
8
+ "type": "module",
9
+ "main": "./src/index.ts",
10
+ "files": ["src", "themes", "README.md", "LICENSE"],
11
+ "keywords": ["pi-package", "pi", "pi-coding-agent", "pi-extension", "pi-theme", "gruvbox-material", "senja", "footer", "header", "tui"],
12
+ "scripts": {
13
+ "typecheck": "tsc -p tsconfig.json --noEmit",
14
+ "test": "bun test test"
15
+ },
16
+ "pi": {
17
+ "extensions": ["./src/index.ts"],
18
+ "themes": ["./themes/senja.json"]
19
+ },
20
+ "peerDependencies": {
21
+ "@earendil-works/pi-ai": "*",
22
+ "@earendil-works/pi-coding-agent": "*",
23
+ "@earendil-works/pi-tui": "*"
24
+ },
25
+ "peerDependenciesMeta": {
26
+ "@earendil-works/pi-ai": { "optional": true },
27
+ "@earendil-works/pi-coding-agent": { "optional": true },
28
+ "@earendil-works/pi-tui": { "optional": true }
29
+ },
30
+ "devDependencies": {
31
+ "@earendil-works/pi-ai": "^1.0.0",
32
+ "@earendil-works/pi-coding-agent": "^1.0.0",
33
+ "@earendil-works/pi-tui": "^1.0.0",
34
+ "@types/bun": "^1.3.14",
35
+ "typescript": "^7.0.2"
36
+ },
37
+ "repository": {
38
+ "type": "git",
39
+ "url": "https://github.com/arhen/pi-extensions",
40
+ "directory": "packages/add/pi-senja"
41
+ },
42
+ "homepage": "https://github.com/arhen/pi-extensions/tree/main/packages/add/pi-senja#readme",
43
+ "bugs": { "url": "https://github.com/arhen/pi-extensions/issues" },
44
+ "publishConfig": {
45
+ "access": "public",
46
+ "registry": "https://registry.npmjs.org/"
47
+ }
48
+ }
package/src/index.ts ADDED
@@ -0,0 +1,594 @@
1
+ /**
2
+ * Senja — fork of pi-haiku 0.2.0 by nocte (MIT).
3
+ *
4
+ * Layout:
5
+ * • Line 1: location left, provider ▪ model ▪ effort right
6
+ * • Line 2: working/done timer + stats left, context bar + % + size right
7
+ * • Line 3 (optional): raw extension statuses
8
+ *
9
+ * Usage:
10
+ * /senja Toggle on/off
11
+ */
12
+
13
+ import { isAbsolute, relative, resolve, sep } from "node:path";
14
+ import type { AssistantMessage, ThinkingLevel } from "@earendil-works/pi-ai";
15
+ import type { ExtensionAPI, ExtensionContext, Theme, ThemeColor } from "@earendil-works/pi-coding-agent";
16
+ import { VERSION } from "@earendil-works/pi-coding-agent";
17
+ import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
18
+
19
+ // ── Visual primitives ────────────────────────────────────────────────────────
20
+
21
+ const GLYPH = {
22
+ dot: "·",
23
+ square: "▪",
24
+ barFull: "█",
25
+ barEmpty: "░",
26
+ bracketL: "[",
27
+ bracketR: "]",
28
+ pipe: "|",
29
+ } as const;
30
+
31
+ interface RenderHandle {
32
+ requestRender(): void;
33
+ }
34
+
35
+ // ── Helpers ──────────────────────────────────────────────────────────────────
36
+
37
+ /** Replace $HOME with ~, mirroring Pi's built-in footer logic. */
38
+ function formatCwd(cwd: string): string {
39
+ const home = process.env.HOME || process.env.USERPROFILE;
40
+ if (!home) return cwd;
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));
47
+
48
+ if (!insideHome) return cwd;
49
+ return rel === "" ? "~" : `~${sep}${rel}`;
50
+ }
51
+
52
+ /** Compact token formatter. */
53
+ 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`;
59
+ }
60
+
61
+ /** Format milliseconds as a human-readable duration. */
62
+ function formatDuration(ms: number): string {
63
+ const totalSeconds = Math.max(0, Math.floor(ms / 1000));
64
+ if (totalSeconds < 60) return `${totalSeconds}s`;
65
+
66
+ const s = totalSeconds % 60;
67
+ const totalMinutes = Math.floor(totalSeconds / 60);
68
+ if (totalMinutes < 60) return `${totalMinutes}m ${s}s`;
69
+
70
+ const m = totalMinutes % 60;
71
+ const h = Math.floor(totalMinutes / 60);
72
+ return `${h}h ${m}m ${s}s`;
73
+ }
74
+
75
+ /** Right-align two text blocks, truncating left if they don't both fit. */
76
+ 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;
90
+ }
91
+
92
+ /** Theme color for a provider name. */
93
+ 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
+ }
117
+ }
118
+
119
+ /** Theme color for an effort/thinking level. */
120
+ 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
+ }
137
+ }
138
+
139
+ /** Color scale for percentage values (context usage / cache hit). */
140
+ function stressColor(value: number, warn = 70, danger = 90): ThemeColor {
141
+ if (value >= danger) return "error";
142
+ if (value >= warn) return "warning";
143
+ return "accent";
144
+ }
145
+
146
+ /** Color scale for cache-hit percentage: low is red, high is green. */
147
+ function cacheHitColor(value: number): ThemeColor {
148
+ if (value < 30) return "error";
149
+ if (value < 70) return "warning";
150
+ return "success";
151
+ }
152
+
153
+ /** Render a horizontal progress bar. */
154
+ 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
+ );
165
+ }
166
+
167
+ 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();
175
+ }
176
+
177
+ 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));
270
+ }
271
+
272
+ 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
+ }));
279
+ }
280
+
281
+ function restoreHeader(ctx: ExtensionContext): void {
282
+ ctx.ui.setHeader(undefined);
283
+ }
284
+
285
+ /** Clear the visible screen and home the cursor on initial launch.
286
+ *
287
+ * This pushes the shell prompt and pre-Pi output out of view while keeping the
288
+ * normal screen buffer, so the mouse wheel can still scroll the terminal page.
289
+ * Scrollback is preserved.
290
+ */
291
+ function clearVisibleScreenOnStartup(): void {
292
+ if (process.stdout.isTTY) {
293
+ process.stdout.write("\x1b[2J\x1b[H");
294
+ }
295
+ }
296
+
297
+ // ── Extension ────────────────────────────────────────────────────────────────
298
+
299
+ 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
+
307
+ function requestFooterRender(): void {
308
+ renderHandle?.requestRender();
309
+ }
310
+
311
+ function clearWorkingTimers(): void {
312
+ if (workingTimer !== undefined) {
313
+ clearInterval(workingTimer);
314
+ workingTimer = undefined;
315
+ }
316
+ }
317
+
318
+ // Re-render when state that the footer displays changes.
319
+ pi.on("thinking_level_select", requestFooterRender);
320
+ pi.on("model_select", requestFooterRender);
321
+
322
+ // Track how long the current prompt has been running.
323
+ pi.on("agent_start", (_event, ctx) => {
324
+ clearWorkingTimers();
325
+ workingSince = Date.now();
326
+ lastDoneIn = undefined;
327
+
328
+ if (ctx.mode !== "tui") return;
329
+
330
+ const tick = () => {
331
+ if (workingSince === undefined) return;
332
+ const elapsed = formatDuration(Date.now() - workingSince);
333
+ try {
334
+ ctx.ui.setWorkingMessage(`Working… ${elapsed}`);
335
+ } catch {
336
+ // Ignore if the UI is already torn down.
337
+ }
338
+ requestFooterRender();
339
+ };
340
+
341
+ tick();
342
+ workingTimer = setInterval(tick, 250);
343
+ });
344
+
345
+ // Report final duration and clean up timers.
346
+ pi.on("agent_end", (_event, ctx) => {
347
+ clearWorkingTimers();
348
+
349
+ if (workingSince !== undefined) {
350
+ lastDoneIn = Date.now() - workingSince;
351
+ workingSince = undefined;
352
+ }
353
+
354
+ requestFooterRender();
355
+
356
+ // Show a notification and working message with the total elapsed time.
357
+ // The working message area may be hidden after streaming ends, so we
358
+ // make it visible first. The footer also displays this until the next task.
359
+ if (lastDoneIn !== undefined && ctx.mode === "tui") {
360
+ try {
361
+ ctx.ui.setWorkingVisible(true);
362
+ ctx.ui.setWorkingMessage(`Worked for ${formatDuration(lastDoneIn)}`);
363
+ ctx.ui.notify(`Worked for ${formatDuration(lastDoneIn)}`, "info");
364
+ } catch {
365
+ // Ignore if the UI is already torn down.
366
+ }
367
+ }
368
+ });
369
+
370
+ function applyFooter(ctx: ExtensionContext): void {
371
+ disposeFooter?.();
372
+ ctx.ui.setFooter((tui, theme, footerData) => {
373
+ disposeFooter?.();
374
+ renderHandle = tui;
375
+ const unsubscribeBranch = footerData.onBranchChange(() => tui.requestRender());
376
+ let disposed = false;
377
+ const dispose = () => {
378
+ if (disposed) return;
379
+ disposed = true;
380
+ unsubscribeBranch();
381
+ if (disposeFooter === dispose) {
382
+ disposeFooter = undefined;
383
+ renderHandle = undefined;
384
+ }
385
+ };
386
+ disposeFooter = dispose;
387
+
388
+ return {
389
+ dispose,
390
+ invalidate() {
391
+ // Stateless render; nothing to cache.
392
+ },
393
+ render(width: number): string[] {
394
+ if (width <= 0) return [];
395
+ // ── Aggregate usage across every assistant message ───────────────
396
+ let totalInput = 0;
397
+ let totalOutput = 0;
398
+ let totalCacheRead = 0;
399
+ let totalCacheWrite = 0;
400
+ let totalCost = 0;
401
+ let latestCacheHitRate: number | undefined;
402
+
403
+ for (const entry of ctx.sessionManager.getEntries()) {
404
+ if (entry.type === "message" && entry.message.role === "assistant") {
405
+ const m = entry.message as AssistantMessage;
406
+ totalInput += m.usage.input;
407
+ totalOutput += m.usage.output;
408
+ totalCacheRead += m.usage.cacheRead;
409
+ totalCacheWrite += m.usage.cacheWrite;
410
+ totalCost += m.usage.cost.total;
411
+
412
+ const promptTokens = m.usage.input + m.usage.cacheRead + m.usage.cacheWrite;
413
+ latestCacheHitRate =
414
+ promptTokens > 0 ? (m.usage.cacheRead / promptTokens) * 100 : undefined;
415
+ }
416
+ }
417
+
418
+ // ── Context usage for the active model ───────────────────────────
419
+ const contextUsage = ctx.getContextUsage();
420
+ const contextWindow = contextUsage?.contextWindow ?? ctx.model?.contextWindow ?? 0;
421
+ const contextTokens = contextUsage?.tokens ?? null;
422
+ const contextPercent = contextUsage?.percent ?? null;
423
+ const contextPctValue = contextPercent ?? 0;
424
+
425
+ // ── Location / session metadata ──────────────────────────────────
426
+ const cwd = sanitizeStatus(formatCwd(ctx.sessionManager.getCwd()));
427
+ const branch = sanitizeStatus(footerData.getGitBranch() ?? "");
428
+ const sessionName = sanitizeStatus(ctx.sessionManager.getSessionName() ?? "");
429
+
430
+ // ── Provider / model / effort metadata ───────────────────────────
431
+ const provider = sanitizeStatus(ctx.model?.provider ?? "none");
432
+ const modelId = sanitizeStatus(ctx.model?.id ?? "no-model");
433
+ const reasoning = ctx.model?.reasoning ?? false;
434
+ const usingSubscription = ctx.model ? ctx.modelRegistry.isUsingOAuth(ctx.model) : false;
435
+
436
+ // ── Line 1: location left, provider ▪ model ▪ effort right ───────
437
+ let locationBlock = theme.fg("accent", cwd);
438
+ if (branch) {
439
+ locationBlock += ` ${theme.fg("dim", "branch")} ${theme.fg("success", branch)}`;
440
+ }
441
+ if (sessionName) {
442
+ locationBlock += ` ${theme.fg("dim", "session")} ${theme.fg("text", sessionName)}`;
443
+ }
444
+
445
+ let modelBlock = `${theme.fg(providerColor(provider), String(provider))} ${theme.fg("dim", GLYPH.square)} ${theme.fg("text", modelId)}`;
446
+ if (reasoning) {
447
+ const level = pi.getThinkingLevel();
448
+ modelBlock += ` ${theme.fg("dim", GLYPH.square)} ${theme.fg(effortColor(level), level)}`;
449
+ }
450
+
451
+ const line1 = alignRight(locationBlock, modelBlock, width, theme);
452
+
453
+ // ── Line 2: working/done timer + stats left, context right ───────
454
+ const stats: string[] = [];
455
+
456
+ if (totalInput > 0) {
457
+ stats.push(`${theme.fg("dim", "in")} ${theme.fg("accent", `↑${fmtTokens(totalInput)}`)}`);
458
+ }
459
+ if (totalOutput > 0) {
460
+ stats.push(`${theme.fg("dim", "out")} ${theme.fg("success", `↓${fmtTokens(totalOutput)}`)}`);
461
+ }
462
+ if (latestCacheHitRate !== undefined) {
463
+ stats.push(
464
+ `${theme.fg("dim", "cache hit")} ${theme.fg(
465
+ cacheHitColor(latestCacheHitRate),
466
+ `${latestCacheHitRate.toFixed(1)}%`,
467
+ )}`,
468
+ );
469
+ }
470
+
471
+ if (totalCost > 0) {
472
+ const costText = `$${totalCost.toFixed(3)}${usingSubscription ? " (sub)" : ""}`;
473
+ stats.push(`${theme.fg("dim", "cost")} ${theme.fg("warning", costText)}`);
474
+ }
475
+
476
+ const statsBlock = stats.join(` ${theme.fg("dim", GLYPH.pipe)} `);
477
+
478
+ let contextBlock = "";
479
+ if (contextTokens !== null && contextTokens > 0) {
480
+ const pctText = theme.fg(stressColor(contextPctValue, 70, 90), `${contextPctValue.toFixed(1)}%`);
481
+ const contextText = `${theme.fg("text", fmtTokens(contextTokens))}${theme.fg("dim", "/")}${theme.fg("text", fmtTokens(contextWindow))}`;
482
+ // Fit the context block within the available width so the right-hand
483
+ // numbers aren't truncated (e.g. 50k/500k becoming 50k/5...).
484
+ const reserved = visibleWidth(pctText) + visibleWidth(contextText) + 4 + 2; // separators + brackets
485
+ const barWidth = Math.max(6, Math.min(16, width - reserved));
486
+ contextBlock = `${renderBar(theme, contextPctValue, barWidth)} ${pctText} ${theme.fg("dim", GLYPH.square)} ${contextText}`;
487
+ }
488
+
489
+ let timerBlock = "";
490
+ if (workingSince !== undefined) {
491
+ timerBlock = `${theme.fg("dim", "working")} ${theme.fg("accent", formatDuration(Date.now() - workingSince))}`;
492
+ } else if (lastDoneIn !== undefined) {
493
+ timerBlock = `${theme.fg("success", "worked")} ${theme.fg("text", `for ${formatDuration(lastDoneIn)}`)}`;
494
+ }
495
+
496
+ let rightBlock = statsBlock;
497
+ if (contextBlock) {
498
+ rightBlock = rightBlock ? alignRight(rightBlock, contextBlock, width, theme) : contextBlock;
499
+ }
500
+
501
+ let line2: string | undefined;
502
+ if (timerBlock && rightBlock) {
503
+ line2 = alignRight(timerBlock, rightBlock, width, theme);
504
+ } else if (timerBlock) {
505
+ line2 = timerBlock;
506
+ } else if (rightBlock) {
507
+ line2 = rightBlock;
508
+ }
509
+
510
+ // ── Optional line 3: raw extension statuses ──────────────────────
511
+ const lines: string[] = [line1];
512
+ if (line2) {
513
+ lines.push(line2);
514
+ }
515
+ const extensionStatuses = footerData.getExtensionStatuses();
516
+
517
+ if (extensionStatuses.size > 0) {
518
+ const divider = ` ${GLYPH.pipe} `;
519
+ const rawStatuses = Array.from(extensionStatuses.entries())
520
+ .sort(([a], [b]) => a.localeCompare(b))
521
+ .map(([, text]) => sanitizeStatus(text))
522
+ .filter((text) => text.length > 0)
523
+ .join(divider);
524
+ if (rawStatuses) {
525
+ lines.push(theme.fg("dim", rawStatuses));
526
+ }
527
+ }
528
+
529
+ // Truncate every line to exact terminal width; no trailing spacing.
530
+ return lines.map((line) => truncateToWidth(line, width, theme.fg("dim", "…")));
531
+ },
532
+ };
533
+ });
534
+ }
535
+
536
+ function restoreFooter(ctx: ExtensionContext): void {
537
+ disposeFooter?.();
538
+ ctx.ui.setFooter(undefined);
539
+ }
540
+
541
+ // Toggle command.
542
+ pi.registerCommand("senja", {
543
+ description: "Toggle the Senja header and footer",
544
+ handler: async (_args, ctx) => {
545
+ if (ctx.mode !== "tui") {
546
+ if (ctx.hasUI) ctx.ui.notify("Senja requires terminal UI mode", "info");
547
+ return;
548
+ }
549
+ enabled = !enabled;
550
+ if (enabled) {
551
+ applyFooter(ctx);
552
+ applyHeader(ctx);
553
+ ctx.ui.notify("Senja enabled", "info");
554
+ } else {
555
+ restoreFooter(ctx);
556
+ restoreHeader(ctx);
557
+ ctx.ui.notify("Default UI restored", "info");
558
+ }
559
+ },
560
+ });
561
+
562
+ pi.on("session_start", (event, ctx) => {
563
+ clearWorkingTimers();
564
+ workingSince = undefined;
565
+ lastDoneIn = undefined;
566
+ disposeFooter?.();
567
+ if (ctx.mode !== "tui") return;
568
+
569
+ if (event.reason === "startup") {
570
+ clearVisibleScreenOnStartup();
571
+ }
572
+
573
+ const result = ctx.ui.setTheme("senja");
574
+ if (!result.success) {
575
+ ctx.ui.notify(`Senja theme: ${result.error ?? "unknown error"}`, "warning");
576
+ }
577
+
578
+ if (enabled) {
579
+ applyFooter(ctx);
580
+ applyHeader(ctx);
581
+ } else {
582
+ restoreFooter(ctx);
583
+ restoreHeader(ctx);
584
+ }
585
+ });
586
+
587
+ pi.on("session_shutdown", () => {
588
+ clearWorkingTimers();
589
+ workingSince = undefined;
590
+ lastDoneIn = undefined;
591
+ disposeFooter?.();
592
+ renderHandle = undefined;
593
+ });
594
+ }
@@ -0,0 +1,104 @@
1
+ {
2
+ "$schema": "https://raw.githubusercontent.com/earendil-works/pi/main/packages/coding-agent/src/modes/interactive/theme/theme-schema.json",
3
+ "name": "senja",
4
+ "appearance": "dark",
5
+ "vars": {
6
+ "bg_dim": "#1b1b1b",
7
+ "bg0": "#282828",
8
+ "bg1": "#32302f",
9
+ "bg2": "#32302f",
10
+ "bg3": "#45403d",
11
+ "bg4": "#45403d",
12
+ "bg5": "#5a524c",
13
+ "bg_current_word": "#3c3836",
14
+ "bg_diff_blue": "#0e363e",
15
+ "bg_diff_green": "#34381b",
16
+ "bg_diff_red": "#402120",
17
+ "bg_statusline1": "#32302f",
18
+ "bg_statusline2": "#3a3735",
19
+ "bg_statusline3": "#504945",
20
+ "bg_visual_blue": "#374141",
21
+ "bg_visual_green": "#3b4439",
22
+ "bg_visual_red": "#4c3432",
23
+ "bg_visual_yellow": "#4f422e",
24
+ "bg_visual_purple": "#443840",
25
+ "bg_green": "#a9b665",
26
+ "bg_red": "#ea6962",
27
+ "bg_yellow": "#d8a657",
28
+ "fg0": "#d4be98",
29
+ "fg1": "#ddc7a1",
30
+ "grey0": "#7c6f64",
31
+ "grey1": "#928374",
32
+ "grey2": "#a89984",
33
+ "red": "#ea6962",
34
+ "orange": "#e78a4e",
35
+ "yellow": "#d8a657",
36
+ "green": "#a9b665",
37
+ "aqua": "#89b482",
38
+ "blue": "#7daea3",
39
+ "purple": "#d3869b"
40
+ },
41
+ "colors": {
42
+ "accent": "orange",
43
+ "border": "grey1",
44
+ "borderAccent": "orange",
45
+ "borderMuted": "bg5",
46
+ "success": "green",
47
+ "error": "red",
48
+ "warning": "yellow",
49
+ "muted": "grey2",
50
+ "dim": "grey1",
51
+ "text": "fg0",
52
+ "thinkingText": "grey2",
53
+ "selectedBg": "bg3",
54
+ "scrollbarTrack": "grey0",
55
+ "scrollbarThumb": "fg0",
56
+ "searchMatchBg": "green",
57
+ "searchMatchText": "bg0",
58
+ "userMessageBg": "bg1",
59
+ "userMessageText": "fg0",
60
+ "customMessageBg": "bg_visual_blue",
61
+ "customMessageText": "fg0",
62
+ "customMessageLabel": "blue",
63
+ "toolPendingBg": "bg1",
64
+ "toolSuccessBg": "bg_visual_green",
65
+ "toolErrorBg": "bg_visual_red",
66
+ "toolTitle": "fg0",
67
+ "toolOutput": "fg0",
68
+ "mdHeading": "orange",
69
+ "mdLink": "blue",
70
+ "mdLinkUrl": "grey2",
71
+ "mdCode": "green",
72
+ "mdCodeBlock": "fg0",
73
+ "mdCodeBlockBorder": "grey1",
74
+ "mdQuote": "grey2",
75
+ "mdQuoteBorder": "grey1",
76
+ "mdHr": "grey1",
77
+ "mdListBullet": "orange",
78
+ "toolDiffAdded": "green",
79
+ "toolDiffRemoved": "red",
80
+ "toolDiffContext": "grey2",
81
+ "syntaxComment": "grey1",
82
+ "syntaxKeyword": "red",
83
+ "syntaxFunction": "green",
84
+ "syntaxVariable": "fg0",
85
+ "syntaxString": "aqua",
86
+ "syntaxNumber": "purple",
87
+ "syntaxType": "yellow",
88
+ "syntaxOperator": "orange",
89
+ "syntaxPunctuation": "grey2",
90
+ "thinkingOff": "grey0",
91
+ "thinkingMinimal": "grey2",
92
+ "thinkingLow": "blue",
93
+ "thinkingMedium": "aqua",
94
+ "thinkingHigh": "yellow",
95
+ "thinkingXhigh": "orange",
96
+ "thinkingMax": "purple",
97
+ "bashMode": "green"
98
+ },
99
+ "export": {
100
+ "pageBg": "bg0",
101
+ "cardBg": "bg1",
102
+ "infoBg": "bg_dim"
103
+ }
104
+ }