pi-sakura-cyberdeck 1.5.2 → 1.5.4

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.
Files changed (34) hide show
  1. package/CHANGELOG.md +124 -0
  2. package/README.md +36 -18
  3. package/README.zh-CN.md +7 -5
  4. package/extensions/changelog/index.ts +186 -42
  5. package/extensions/claude-shimmer/index.ts +336 -140
  6. package/extensions/header/index.ts +84 -41
  7. package/extensions/matrix/index.ts +221 -69
  8. package/extensions/shared/color.ts +90 -36
  9. package/extensions/shared/config-file.ts +324 -0
  10. package/extensions/shared/tui-context.ts +78 -0
  11. package/extensions/zentui/config.ts +87 -128
  12. package/extensions/zentui/extension-status.ts +158 -19
  13. package/extensions/zentui/footer-format.ts +279 -85
  14. package/extensions/zentui/footer-segments.ts +630 -0
  15. package/extensions/zentui/footer.ts +668 -525
  16. package/extensions/zentui/format.ts +43 -19
  17. package/extensions/zentui/git.ts +362 -167
  18. package/extensions/zentui/gradient.ts +100 -50
  19. package/extensions/zentui/index.ts +172 -59
  20. package/extensions/zentui/live-context.ts +2 -1
  21. package/extensions/zentui/package-version.ts +102 -14
  22. package/extensions/zentui/project-refresh.ts +42 -20
  23. package/extensions/zentui/project-state.ts +2 -2
  24. package/extensions/zentui/runtime.ts +140 -51
  25. package/extensions/zentui/selector-border.ts +96 -16
  26. package/extensions/zentui/session-lifecycle.ts +3 -1
  27. package/extensions/zentui/settings-command.ts +404 -246
  28. package/extensions/zentui/shell-call.ts +140 -26
  29. package/extensions/zentui/style.ts +109 -40
  30. package/extensions/zentui/thinking-trail.ts +234 -9
  31. package/extensions/zentui/tool-execution.ts +144 -64
  32. package/extensions/zentui/ui.ts +698 -145
  33. package/extensions/zentui/user-message.ts +24 -12
  34. package/package.json +2 -1
@@ -1,30 +1,44 @@
1
- import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
- import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
3
- import { fgAnsi, getColorMode, syncColorMode, type RGB } from "../shared/color";
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import { fgAnsi, getColorMode, syncColorMode, type ColorMode, type RGB } from "../shared/color";
3
+ import { isInteractiveTui, mixRgb, normalizeWidth } from "../shared/tui-context";
4
4
 
5
5
  const SAKURA: RGB = [242, 167, 198];
6
6
  const PEACH: RGB = [246, 188, 154];
7
7
  const LAVENDER: RGB = [199, 184, 245];
8
8
  const SKY: RGB = [159, 211, 242];
9
9
  const LABEL = "◈ SAKURA CYBERDECK ◈";
10
+ const LABEL_CHARS = [...LABEL];
11
+ const LABEL_WIDTH = LABEL_CHARS.length;
10
12
  /** Fixed blank rows above the artwork (independent of terminal height). */
11
13
  export const TOP_PADDING = 1;
12
14
 
13
15
  function gradient(text: string, from: RGB, to: RGB, bold = false): string {
14
- if (getColorMode() === "none") return text;
16
+ const colorMode = getColorMode();
17
+ if (colorMode === "none" || text.length === 0) return text;
15
18
  const chars = [...text];
16
19
  const span = Math.max(1, chars.length - 1);
17
- const open = bold ? "\x1b[1m" : "";
18
- return chars.map((char, index) => {
19
- if (char === " ") return char;
20
- const t = index / span;
21
- const color: RGB = [
22
- Math.round(from[0] + (to[0] - from[0]) * t),
23
- Math.round(from[1] + (to[1] - from[1]) * t),
24
- Math.round(from[2] + (to[2] - from[2]) * t),
25
- ];
26
- return `${open}${fgAnsi(color)}${char}\x1b[0m`;
27
- }).join("");
20
+ const prefix = bold ? "\x1b[1m" : "";
21
+ let out = "";
22
+ let lastAnsi = "";
23
+ for (let index = 0; index < chars.length; index++) {
24
+ const char = chars[index]!;
25
+ if (char === " " || char === "\u2800") {
26
+ if (lastAnsi) {
27
+ out += "\x1b[0m";
28
+ lastAnsi = "";
29
+ }
30
+ out += char;
31
+ continue;
32
+ }
33
+ const ansi = fgAnsi(mixRgb(from, to, index / span), colorMode);
34
+ if (ansi !== lastAnsi) {
35
+ out += lastAnsi ? ansi : `${prefix}${ansi}`;
36
+ lastAnsi = ansi;
37
+ }
38
+ out += char;
39
+ }
40
+ if (lastAnsi) out += "\x1b[0m";
41
+ return out;
28
42
  }
29
43
 
30
44
  const ANIME_ART = [
@@ -49,51 +63,80 @@ function centerPad(width: number, contentWidth: number, nudge = 0): string {
49
63
 
50
64
  /** Header lines; every line fits within `width` columns and the height never depends on the terminal. */
51
65
  export function renderHeader(width: number): string[] {
52
- const w = Math.floor(width);
53
- if (!Number.isFinite(w) || w <= 0) return [];
66
+ const w = normalizeWidth(width);
67
+ if (w <= 0) return [];
54
68
 
55
69
  const artWidth = Math.min(w, ART_WIDTH);
56
70
  const artPad = centerPad(w, artWidth, -2);
57
- // Truncate after coloring: pi-tui's truncateToWidth is ANSI-aware and wide-char safe.
58
- const art = ANIME_ART.map((line) => `${artPad}${truncateToWidth(gradient(line, SAKURA, SKY), artWidth, "")}`);
71
+ // Every ANIME_ART cell is single-column BMP Braille/space, so slicing before painting avoids coloring clipped columns.
72
+ const art = ANIME_ART.map(
73
+ (line) => `${artPad}${gradient(artWidth < line.length ? line.slice(0, artWidth) : line, SAKURA, SKY)}`,
74
+ );
59
75
 
60
76
  // Keep the divider visually subordinate: inset it symmetrically from the artwork.
61
77
  const railInset = artWidth >= 8 ? Math.max(2, Math.round(artWidth * 0.15)) : 0;
62
78
  const railWidth = Math.max(1, artWidth - railInset * 2);
63
79
  const rail = `${centerPad(w, railWidth, 1)}${gradient("━".repeat(railWidth), SAKURA, SKY)}`;
64
80
 
65
- const label = truncateToWidth(gradient(LABEL, LAVENDER, PEACH, true), w, "…");
66
- const labelLine = `${centerPad(w, visibleWidth(label), 1)}${label}`;
81
+ // Every LABEL character and "…" is single-column BMP; slice before painting to avoid ANSI resets in NO_COLOR mode.
82
+ const visibleLabel =
83
+ w >= LABEL_WIDTH
84
+ ? LABEL
85
+ : w === 1
86
+ ? "…"
87
+ : `${LABEL_CHARS.slice(0, w - 1).join("")}…`;
88
+ const label = gradient(visibleLabel, LAVENDER, PEACH, true);
89
+ const labelLine = `${centerPad(w, Math.min(w, LABEL_WIDTH), 1)}${label}`;
67
90
 
68
91
  return [...Array<string>(TOP_PADDING).fill(""), ...art, "", rail, labelLine, ""];
69
92
  }
70
93
 
71
- function isInteractiveTui(ctx: Pick<ExtensionContext, "mode" | "hasUI">): boolean {
72
- return typeof ctx.mode === "string" ? ctx.mode === "tui" : ctx.hasUI === true;
73
- }
74
-
75
94
  export default function sakuraCyberdeckHeader(pi: ExtensionAPI): void {
95
+ let headerToken = 0;
96
+ let headerOwned = false;
97
+
76
98
  pi.on("session_start", (_event, ctx) => {
77
99
  if (!isInteractiveTui(ctx)) return;
78
- syncColorMode(ctx.ui.theme);
79
- let cachedWidth = -1;
80
- let cachedLines: string[] = [];
81
- ctx.ui.setHeader(() => ({
82
- render(width: number): string[] {
83
- if (width !== cachedWidth) {
84
- cachedLines = renderHeader(width);
85
- cachedWidth = width;
86
- }
87
- return cachedLines;
88
- },
89
- invalidate() {
90
- cachedWidth = -1;
91
- },
92
- }));
100
+ syncColorMode(ctx.ui?.theme);
101
+ const token = ++headerToken;
102
+ headerOwned = true;
103
+ try {
104
+ ctx.ui.setHeader(() => {
105
+ let cachedWidth = -1;
106
+ let cachedMode: ColorMode | undefined;
107
+ let cachedLines: string[] = [];
108
+ return {
109
+ render(width: number): string[] {
110
+ const safeWidth = normalizeWidth(width);
111
+ const colorMode = getColorMode();
112
+ if (safeWidth !== cachedWidth || colorMode !== cachedMode) {
113
+ cachedLines = renderHeader(safeWidth);
114
+ cachedWidth = safeWidth;
115
+ cachedMode = colorMode;
116
+ }
117
+ return cachedLines;
118
+ },
119
+ invalidate() {
120
+ cachedWidth = -1;
121
+ cachedMode = undefined;
122
+ },
123
+ dispose() {
124
+ if (token === headerToken) {
125
+ headerOwned = false;
126
+ }
127
+ },
128
+ };
129
+ });
130
+ } catch {
131
+ if (token === headerToken) headerOwned = false;
132
+ }
93
133
  });
94
134
 
95
135
  pi.on("session_shutdown", (_event, ctx) => {
96
- if (!isInteractiveTui(ctx)) return;
136
+ const owned = headerOwned;
137
+ headerToken += 1;
138
+ headerOwned = false;
139
+ if (!owned || !isInteractiveTui(ctx)) return;
97
140
  try {
98
141
  ctx.ui.setHeader(undefined);
99
142
  } catch {
@@ -4,14 +4,24 @@
4
4
  * widget: it never touches Pi's working message/indicator (the shimmer owns those).
5
5
  * One timer runs only while the rain is visible; idle CPU is zero.
6
6
  */
7
- import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
8
- import { dirname, join } from "node:path";
7
+ import { join } from "node:path";
9
8
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
10
9
  import { getAgentDir } from "@earendil-works/pi-coding-agent";
11
- import { fgAnsi, getColorMode, syncColorMode, type RGB } from "../shared/color";
10
+ import { fgAnsi, getColorMode, syncColorMode, type ColorMode, type RGB } from "../shared/color";
11
+ import {
12
+ describeConfigError,
13
+ readJsonConfigFile,
14
+ writeJsonConfigAtomically,
15
+ } from "../shared/config-file";
16
+ import { isInteractiveTui, mixRgb, normalizeWidth } from "../shared/tui-context";
12
17
 
13
18
  const WIDGET_KEY = "sakura-matrix-engine";
14
- export const CONFIG_PATH = join(getAgentDir(), "sakura-cyberdeck-matrix.json");
19
+ const CONFIG_FILENAME = "sakura-cyberdeck-matrix.json";
20
+
21
+ /** Resolve the Matrix config path lazily so Pi `--agent-dir` / `PI_CODING_AGENT_DIR` changes after import take effect. */
22
+ export function getConfigPath(): string {
23
+ return join(getAgentDir(), CONFIG_FILENAME);
24
+ }
15
25
  const PREVIEW_MS = 5_000;
16
26
  const GLYPHS = [..."0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZアイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモラリルレロワン"];
17
27
  const BG: RGB = [20, 17, 26];
@@ -43,6 +53,7 @@ interface Drop {
43
53
  gap: number;
44
54
  seed: number;
45
55
  color: RGB;
56
+ colorIndex?: number;
46
57
  }
47
58
 
48
59
  export const LIMITS = {
@@ -78,25 +89,20 @@ export function normalizeConfig(parsed: unknown): MatrixConfig {
78
89
  };
79
90
  }
80
91
 
81
- export function loadConfig(path = CONFIG_PATH): { config: MatrixConfig; error?: string } {
82
- try {
83
- if (!existsSync(path)) return { config: { ...DEFAULT_CONFIG } };
84
- return { config: normalizeConfig(JSON.parse(readFileSync(path, "utf8"))) };
85
- } catch (error) {
86
- return { config: { ...DEFAULT_CONFIG }, error: error instanceof Error ? error.message : String(error) };
87
- }
92
+ export function loadConfig(path = getConfigPath()): { config: MatrixConfig; error?: string } {
93
+ const state = readJsonConfigFile(path);
94
+ if (state.kind === "missing") return { config: { ...DEFAULT_CONFIG } };
95
+ if (state.kind === "valid") return { config: normalizeConfig(state.record) };
96
+ return { config: { ...DEFAULT_CONFIG }, error: describeConfigError(state.error) };
88
97
  }
89
98
 
90
99
  /** Returns an error message instead of throwing. */
91
- export function saveConfig(config: MatrixConfig, path = CONFIG_PATH): string | undefined {
100
+ export function saveConfig(config: MatrixConfig, path = getConfigPath()): string | undefined {
92
101
  try {
93
- mkdirSync(dirname(path), { recursive: true });
94
- const tmp = `${path}.${process.pid}.tmp`;
95
- writeFileSync(tmp, `${JSON.stringify(config, null, 2)}\n`, "utf8");
96
- renameSync(tmp, path);
102
+ writeJsonConfigAtomically(path, `${JSON.stringify(normalizeConfig(config), null, 2)}\n`);
97
103
  return undefined;
98
104
  } catch (error) {
99
- return error instanceof Error ? error.message : String(error);
105
+ return describeConfigError(error);
100
106
  }
101
107
  }
102
108
 
@@ -119,24 +125,36 @@ export const HELP_TEXT = [
119
125
  ].join("\n");
120
126
 
121
127
  export function parseMatrixCommand(args: string): MatrixCommand {
122
- const [command = "", value] = args.trim().toLowerCase().split(/\s+/);
128
+ const trimmed = typeof args === "string" ? args.trim() : "";
129
+ if (!trimmed) return { type: "status" };
130
+ const tokens = trimmed.toLowerCase().split(/\s+/);
131
+ const command = tokens[0]!;
132
+ const value = tokens[1];
123
133
  switch (command) {
124
- case "":
125
134
  case "status":
135
+ if (tokens.length > 1) {
136
+ return { type: "invalid", message: `Unexpected arguments for "status".\n${HELP_TEXT}` };
137
+ }
126
138
  return { type: "status" };
127
139
  case "help":
128
140
  case "?":
141
+ if (tokens.length > 1) {
142
+ return { type: "invalid", message: `Unexpected arguments for "${command}".\n${HELP_TEXT}` };
143
+ }
129
144
  return { type: "help" };
130
145
  case "on":
131
146
  case "off":
132
147
  case "preview":
148
+ if (tokens.length > 1) {
149
+ return { type: "invalid", message: `Unexpected arguments for "${command}".\n${HELP_TEXT}` };
150
+ }
133
151
  return { type: command };
134
152
  case "fps":
135
153
  case "density":
136
154
  case "height": {
137
155
  const { min, max } = LIMITS[command];
138
156
  const n = Number(value);
139
- if (value === undefined || !Number.isFinite(n) || n < min || n > max) {
157
+ if (tokens.length !== 2 || value === undefined || !Number.isFinite(n) || n < min || n > max) {
140
158
  return { type: "invalid", message: `Usage: /sakura-matrix ${command} <${min}-${max}>` };
141
159
  }
142
160
  const rounded = command === "density" ? Math.round(n * 100) / 100 : Math.round(n);
@@ -162,20 +180,41 @@ function mulberry32(seed: number): () => number {
162
180
  };
163
181
  }
164
182
 
165
- function mix(from: RGB, to: RGB, amount: number): RGB {
166
- return [
167
- Math.round(from[0] + (to[0] - from[0]) * amount),
168
- Math.round(from[1] + (to[1] - from[1]) * amount),
169
- Math.round(from[2] + (to[2] - from[2]) * amount),
170
- ];
171
- }
172
-
173
- function colorize(char: string, color: RGB, bold: boolean): string {
174
- const open = fgAnsi(color);
183
+ function colorize(char: string, color: RGB, bold: boolean, colorMode: ColorMode): string {
184
+ const open = fgAnsi(color, colorMode);
175
185
  if (!open) return char;
176
186
  return `${bold ? "\x1b[1m" : ""}${open}${char}\x1b[0m`;
177
187
  }
178
188
 
189
+ const TRAIL_SLOTS = 8;
190
+ let cachedAnsiTableMode: ColorMode | undefined;
191
+ let cachedAnsiTable: string[] = [];
192
+
193
+ function getAnsiPrefixTable(colorMode: ColorMode): readonly string[] {
194
+ if (cachedAnsiTableMode === colorMode) return cachedAnsiTable;
195
+ const table = new Array<string>(CANDY.length * TRAIL_SLOTS);
196
+ if (colorMode === "none") {
197
+ table.fill("");
198
+ } else {
199
+ for (let ci = 0; ci < CANDY.length; ci++) {
200
+ const base = CANDY[ci]!;
201
+ for (let ti = 0; ti < TRAIL_SLOTS; ti++) {
202
+ const rgb =
203
+ ti === 0
204
+ ? mixRgb(base, TEXT, 0.58)
205
+ : ti === 1
206
+ ? base
207
+ : mixRgb(base, BG, clamp((ti - 1) * 0.16, 0, 0.72));
208
+ const open = fgAnsi(rgb, colorMode);
209
+ table[ci * TRAIL_SLOTS + ti] = open ? `${ti <= 1 ? "\x1b[1m" : ""}${open}` : "";
210
+ }
211
+ }
212
+ }
213
+ cachedAnsiTableMode = colorMode;
214
+ cachedAnsiTable = table;
215
+ return table;
216
+ }
217
+
179
218
  function stableGlyph(seed: number, row: number, timeSlice: number): string {
180
219
  let hash = Math.imul(seed ^ (row + 17), 0x45d9f3b);
181
220
  hash = Math.imul(hash ^ timeSlice, 0x45d9f3b);
@@ -184,9 +223,17 @@ function stableGlyph(seed: number, row: number, timeSlice: number): string {
184
223
  }
185
224
 
186
225
  export function createDrops(width: number, density: number, height: number): Drop[] {
187
- const random = mulberry32((width * 2654435761) ^ 0x53414b55);
188
- const columns = Array.from({ length: Math.ceil(width / 2) }, (_, index) => index * 2);
189
- const active = columns.filter(() => random() < density);
226
+ const safeWidth = normalizeWidth(width);
227
+ if (safeWidth <= 0) return [];
228
+ const safeHeight = Number.isFinite(height)
229
+ ? clamp(Math.round(height), LIMITS.height.min, LIMITS.height.max)
230
+ : DEFAULT_CONFIG.height;
231
+ const safeDensity = Number.isFinite(density)
232
+ ? clamp(density, LIMITS.density.min, LIMITS.density.max)
233
+ : DEFAULT_CONFIG.density;
234
+ const random = mulberry32((safeWidth * 2654435761) ^ 0x53414b55);
235
+ const columns = Array.from({ length: Math.ceil(safeWidth / 2) }, (_, index) => index * 2);
236
+ const active = columns.filter(() => random() < safeDensity);
190
237
  const selected = active.length >= 8 ? active : columns.slice(0, Math.min(columns.length, 8));
191
238
  // Cap at 96 drops, sampled evenly across the width: keeping the first 96 left the right
192
239
  // side of wide terminals dry. Narrower widths keep exactly the same drops as before.
@@ -196,7 +243,8 @@ export function createDrops(width: number, density: number, height: number): Dro
196
243
  return capped.map((x, index) => {
197
244
  const length = 3 + Math.floor(random() * 5);
198
245
  const gap = 1 + Math.floor(random() * 5);
199
- const cycle = height + length + gap;
246
+ const cycle = safeHeight + length + gap;
247
+ const colorIndex = index % CANDY.length;
200
248
  return {
201
249
  x,
202
250
  offset: random() * cycle,
@@ -204,11 +252,16 @@ export function createDrops(width: number, density: number, height: number): Dro
204
252
  length,
205
253
  gap,
206
254
  seed: Math.floor(random() * 0x7fffffff) ^ (index * 7919),
207
- color: CANDY[index % CANDY.length]!,
255
+ color: CANDY[colorIndex]!,
256
+ colorIndex,
208
257
  };
209
258
  });
210
259
  }
211
260
 
261
+ const MAX_REUSABLE_CELLS = 8192;
262
+ let reusableCellBuffer: string[] = [];
263
+ const rowDirty = new Uint8Array(LIMITS.height.max);
264
+
212
265
  export function renderSakuraMatrix(
213
266
  width: number,
214
267
  height: number,
@@ -216,48 +269,94 @@ export function renderSakuraMatrix(
216
269
  phase: Phase,
217
270
  drops: readonly Drop[],
218
271
  ): string[] {
219
- const safeWidth = Math.max(1, Math.floor(width));
220
- const safeHeight = clamp(Math.round(height), LIMITS.height.min, LIMITS.height.max);
221
- const grid: string[][] = Array.from({ length: safeHeight }, () => Array(safeWidth).fill(" "));
222
- const timeSlice = Math.floor(elapsedSeconds * 8);
272
+ const safeWidth = normalizeWidth(width);
273
+ if (safeWidth <= 0) return [];
274
+ const safeHeight = Number.isFinite(height)
275
+ ? clamp(Math.round(height), LIMITS.height.min, LIMITS.height.max)
276
+ : DEFAULT_CONFIG.height;
277
+ const safeElapsed = Number.isFinite(elapsedSeconds) ? Math.max(0, elapsedSeconds) : 0;
278
+ const totalCells = safeHeight * safeWidth;
279
+ let cells: string[];
280
+ if (totalCells <= MAX_REUSABLE_CELLS) {
281
+ if (reusableCellBuffer.length < totalCells) {
282
+ reusableCellBuffer = new Array<string>(totalCells);
283
+ }
284
+ cells = reusableCellBuffer;
285
+ } else {
286
+ cells = new Array<string>(totalCells);
287
+ }
288
+ cells.fill(" ", 0, totalCells);
289
+ rowDirty.fill(0, 0, safeHeight);
290
+
291
+ const colorMode = getColorMode();
292
+ const ansiTable = getAnsiPrefixTable(colorMode);
293
+ const timeSlice = Math.floor(safeElapsed * 8);
223
294
  const phaseSpeed = phase === "tool" ? 1.12 : phase === "thinking" ? 1.06 : 1;
224
295
 
225
296
  for (const drop of drops) {
226
- if (drop.x >= safeWidth) continue;
297
+ if (!Number.isInteger(drop.x) || drop.x < 0 || drop.x >= safeWidth) continue;
227
298
  const cycle = safeHeight + drop.length + drop.gap;
228
- const head = ((drop.offset + elapsedSeconds * drop.speed * phaseSpeed) % cycle) - drop.gap;
299
+ if (!Number.isFinite(cycle) || cycle <= 0) continue;
300
+ const head = ((drop.offset + safeElapsed * drop.speed * phaseSpeed) % cycle) - drop.gap;
301
+ const ci = drop.colorIndex;
302
+ const hasTableEntry = ci !== undefined && Number.isInteger(ci) && ci >= 0 && ci < CANDY.length;
229
303
  for (let trail = 0; trail < drop.length; trail++) {
230
304
  const row = Math.floor(head - trail);
231
- if (row < 0 || row >= safeHeight) continue;
305
+ if (!Number.isInteger(row) || row < 0 || row >= safeHeight) continue;
232
306
  const glyph = stableGlyph(drop.seed + trail * 97, row, timeSlice);
233
- const color = trail === 0
234
- ? mix(drop.color, TEXT, 0.58)
235
- : trail === 1
236
- ? drop.color
237
- : mix(drop.color, BG, clamp((trail - 1) * 0.16, 0, 0.72));
238
- grid[row]![drop.x] = colorize(glyph, color, trail <= 1);
307
+ let cell: string;
308
+ if (hasTableEntry) {
309
+ const prefix = ansiTable[ci * TRAIL_SLOTS + (trail < TRAIL_SLOTS ? trail : TRAIL_SLOTS - 1)]!;
310
+ cell = prefix ? `${prefix}${glyph}\x1b[0m` : glyph;
311
+ } else {
312
+ const color = trail === 0
313
+ ? mixRgb(drop.color, TEXT, 0.58)
314
+ : trail === 1
315
+ ? drop.color
316
+ : mixRgb(drop.color, BG, clamp((trail - 1) * 0.16, 0, 0.72));
317
+ cell = colorize(glyph, color, trail <= 1, colorMode);
318
+ }
319
+ cells[row * safeWidth + drop.x] = cell;
320
+ rowDirty[row] = 1;
239
321
  }
240
322
  }
241
323
 
242
- const reset = getColorMode() === "none" ? "" : "\x1b[0m";
243
- return grid.map((row) => `${row.join("")}${reset}`);
324
+ const blankRow = " ".repeat(safeWidth);
325
+ const lines = new Array<string>(safeHeight);
326
+ for (let row = 0; row < safeHeight; row++) {
327
+ if (rowDirty[row] === 0) {
328
+ lines[row] = blankRow;
329
+ continue;
330
+ }
331
+ const base = row * safeWidth;
332
+ let line = "";
333
+ for (let col = 0; col < safeWidth; col++) {
334
+ line += cells[base + col]!;
335
+ }
336
+ lines[row] = line;
337
+ }
338
+ return lines;
244
339
  }
245
340
 
246
- function isInteractiveTui(ctx: Pick<ExtensionContext, "mode" | "hasUI">): boolean {
247
- return typeof ctx.mode === "string" ? ctx.mode === "tui" : ctx.hasUI === true;
341
+ function isContextIdle(ctx: ExtensionContext): boolean {
342
+ try {
343
+ return typeof ctx.isIdle === "function" ? ctx.isIdle() : true;
344
+ } catch {
345
+ return true;
346
+ }
248
347
  }
249
348
 
250
349
  export default function sakuraMatrixExtension(pi: ExtensionAPI): void {
251
- const loaded = loadConfig();
252
- const config = loaded.config;
253
- let configWarning = loaded.error
254
- ? `Sakura Matrix: could not read ${CONFIG_PATH} (${loaded.error}); using defaults. Changing a setting will overwrite that file.`
255
- : undefined;
350
+ let config: MatrixConfig = { ...DEFAULT_CONFIG };
351
+ let loadedConfigPath: string | undefined;
352
+ let configWarning: string | undefined;
256
353
 
257
354
  let activeContext: ExtensionContext | undefined;
258
355
  let phase: Phase = "working";
259
356
  let active = false;
260
357
  let previewing = false;
358
+ let promptPaused = false;
359
+ let promptPausedAt = 0;
261
360
  let timer: Timer | undefined;
262
361
  let previewTimer: Timer | undefined;
263
362
  let startedAt = 0;
@@ -275,10 +374,30 @@ export default function sakuraMatrixExtension(pi: ExtensionAPI): void {
275
374
  cachedLines = [];
276
375
  };
277
376
 
377
+ const reloadConfig = (force = false) => {
378
+ const path = getConfigPath();
379
+ if (!force && loadedConfigPath === path) return;
380
+ const loaded = loadConfig(path);
381
+ config = loaded.config;
382
+ loadedConfigPath = path;
383
+ dropsByWidth.clear();
384
+ invalidate();
385
+ configWarning = loaded.error
386
+ ? `Sakura Matrix: could not read ${path} (${loaded.error}); using defaults. Changing a setting will overwrite that file.`
387
+ : undefined;
388
+ };
389
+
278
390
  const component = {
279
391
  render(width: number): string[] {
280
- const safeWidth = Math.max(1, width);
281
- const key = `${safeWidth}:${config.height}:${frame}:${phase}`;
392
+ const safeWidth = normalizeWidth(width);
393
+ if (safeWidth <= 0) {
394
+ if (cachedKey === "0") return cachedLines;
395
+ cachedLines = [];
396
+ cachedKey = "0";
397
+ return cachedLines;
398
+ }
399
+ const colorMode = getColorMode();
400
+ const key = `${safeWidth}:${config.height}:${frame}:${phase}:${colorMode}`;
282
401
  if (key === cachedKey) return cachedLines;
283
402
  let drops = dropsByWidth.get(safeWidth);
284
403
  if (!drops) {
@@ -304,13 +423,13 @@ export default function sakuraMatrixExtension(pi: ExtensionAPI): void {
304
423
  };
305
424
 
306
425
  const schedule = (token: number) => {
307
- if (!active || token !== generation) return;
426
+ if (!active || promptPaused || token !== generation) return;
308
427
  const frameMs = 1000 / config.fps;
309
428
  const now = performance.now();
310
429
  if (now - nextDeadline > frameMs * 3) nextDeadline = now;
311
430
  nextDeadline += frameMs;
312
431
  timer = setTimeout(() => {
313
- if (!active || token !== generation) return;
432
+ if (!active || promptPaused || token !== generation) return;
314
433
  frame += 1;
315
434
  invalidate();
316
435
  // Streaming/tool updates already trigger a host render; skip a redundant one.
@@ -342,7 +461,7 @@ export default function sakuraMatrixExtension(pi: ExtensionAPI): void {
342
461
  const start = (ctx: ExtensionContext, initialPhase: Phase = "working"): boolean => {
343
462
  stop();
344
463
  if (!isInteractiveTui(ctx)) return false;
345
- syncColorMode(ctx.ui.theme);
464
+ syncColorMode(ctx.ui?.theme);
346
465
  activeContext = ctx;
347
466
  active = true;
348
467
  phase = initialPhase;
@@ -378,20 +497,26 @@ export default function sakuraMatrixExtension(pi: ExtensionAPI): void {
378
497
 
379
498
  const notify = (ctx: ExtensionContext, message: string, type: "info" | "warning" | "error" = "info") => {
380
499
  try {
381
- ctx.ui.notify(message, type);
500
+ ctx?.ui?.notify?.(message, type);
382
501
  } catch {}
383
502
  };
384
503
 
385
504
  const persist = (ctx: ExtensionContext, done: string) => {
386
- const error = saveConfig(config);
505
+ const path = getConfigPath();
506
+ const error = saveConfig(config, path);
507
+ loadedConfigPath = path;
387
508
  if (error) notify(ctx, `${done} (not saved: ${error})`, "warning");
388
509
  else notify(ctx, done);
389
510
  configWarning = undefined;
390
511
  };
391
512
 
392
513
  pi.on("session_start", (_event, ctx) => {
514
+ stop();
515
+ promptPaused = false;
516
+ promptPausedAt = 0;
517
+ reloadConfig(true);
393
518
  if (!isInteractiveTui(ctx)) return;
394
- syncColorMode(ctx.ui.theme);
519
+ syncColorMode(ctx.ui?.theme);
395
520
  if (configWarning) {
396
521
  notify(ctx, configWarning, "warning");
397
522
  configWarning = undefined;
@@ -399,16 +524,42 @@ export default function sakuraMatrixExtension(pi: ExtensionAPI): void {
399
524
  });
400
525
 
401
526
  pi.on("agent_start", (_event, ctx) => {
527
+ reloadConfig();
402
528
  if (config.enabled) start(ctx);
403
529
  });
404
530
  pi.on("agent_end", () => stop());
405
531
  pi.on("agent_settled", () => stop());
406
- pi.on("session_shutdown", () => stop());
532
+ pi.on("session_shutdown", () => {
533
+ stop();
534
+ promptPaused = false;
535
+ promptPausedAt = 0;
536
+ });
537
+
538
+ pi.on("ui_prompt_start", () => {
539
+ if (promptPaused) return;
540
+ promptPaused = true;
541
+ promptPausedAt = performance.now();
542
+ if (timer) {
543
+ clearTimeout(timer);
544
+ timer = undefined;
545
+ }
546
+ });
547
+
548
+ pi.on("ui_prompt_end", () => {
549
+ if (!promptPaused) return;
550
+ const pausedMs = Math.max(0, performance.now() - promptPausedAt);
551
+ promptPaused = false;
552
+ promptPausedAt = 0;
553
+ if (!active) return;
554
+ startedAt += pausedMs;
555
+ nextDeadline = performance.now();
556
+ schedule(generation);
557
+ });
407
558
 
408
559
  pi.on("message_update", (event) => {
409
560
  if (!active) return;
410
561
  noteHostUpdate();
411
- const type = (event.assistantMessageEvent as { type?: string } | undefined)?.type;
562
+ const type = (event?.assistantMessageEvent as { type?: string } | undefined)?.type;
412
563
  if (type === "thinking_start" || type === "thinking_delta") setPhase("thinking");
413
564
  else if (type === "thinking_end" || type === "text_delta") setPhase("working");
414
565
  });
@@ -420,6 +571,7 @@ export default function sakuraMatrixExtension(pi: ExtensionAPI): void {
420
571
  pi.registerCommand("sakura-matrix", {
421
572
  description: "Sakura Matrix rain: status | on | off | preview | fps N | density N | height N | help",
422
573
  handler: async (args, ctx) => {
574
+ reloadConfig();
423
575
  const command = parseMatrixCommand(args ?? "");
424
576
  switch (command.type) {
425
577
  case "status":
@@ -434,13 +586,13 @@ export default function sakuraMatrixExtension(pi: ExtensionAPI): void {
434
586
  case "on":
435
587
  config.enabled = true;
436
588
  // Takes effect from the next agent run (or immediately when one is running).
437
- if (previewing && !ctx.isIdle()) {
589
+ if (previewing && !isContextIdle(ctx)) {
438
590
  // Commands run mid-stream: adopt the running preview as the run's rain so its
439
591
  // 5 s timer cannot stop it. An idle preview still expires on its own.
440
592
  if (previewTimer) clearTimeout(previewTimer);
441
593
  previewTimer = undefined;
442
594
  previewing = false;
443
- } else if (!active && !ctx.isIdle()) start(ctx);
595
+ } else if (!active && !isContextIdle(ctx)) start(ctx);
444
596
  persist(ctx, "Sakura Matrix enabled");
445
597
  return;
446
598
  case "off":