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