@xmoon76/dsh-pi-tui 0.5.4 → 0.5.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/README.en.md +46 -42
  2. package/README.md +46 -27
  3. package/cordis.patch.yml +77 -7
  4. package/dist/bootstrap-DQ4YPL-7.mjs +113583 -0
  5. package/dist/builtins.mjs +3 -9
  6. package/dist/{runtime-vc4mdr-R.mjs → client-bootstrap-Cr1JCaF5.mjs} +3670 -2277
  7. package/dist/disposal-BYBbEpVY.mjs +54 -0
  8. package/dist/dist-CIsR7cz4.mjs +15717 -0
  9. package/dist/{entry-control-DvSrndWd.mjs → entry-control-DnduyDiw.mjs} +12 -31
  10. package/dist/{extensions-CcuMY4n2.mjs → extensions-Bp0L37lP.mjs} +1239 -271
  11. package/dist/extensions.mjs +1 -1
  12. package/dist/host-bootstrap-DilsvA6f.mjs +281 -0
  13. package/dist/host-foundation-probe--5jtvHVe.mjs +413 -0
  14. package/dist/host-runtime.d.mts +30 -0
  15. package/dist/host-runtime.mjs +1317 -0
  16. package/dist/index.d.mts +19 -18
  17. package/dist/index.mjs +18410 -8836
  18. package/dist/local-client.mjs +2027 -187
  19. package/dist/local-discovery-C9VMjc0K.mjs +759 -0
  20. package/dist/local-discovery-CDaQHA_R.mjs +2 -0
  21. package/dist/local-host.mjs +1088 -87
  22. package/dist/local-transport-BVwFYq_Y.mjs +513 -0
  23. package/dist/{context-summary-DAisTA_7.mjs → pasted-path-range-CMnxuGPx.mjs} +7613 -216
  24. package/dist/pasted-path-range-r6qzV_tC.mjs +17510 -0
  25. package/dist/performance-host.d.mts +2 -2
  26. package/dist/performance-host.mjs +258 -1
  27. package/dist/pi-tui-remote-contribution-B0EQsP0N.mjs +85 -0
  28. package/dist/pi-tui-terminal-progress-contract-CdBH9j78.mjs +70 -0
  29. package/dist/pi-tui-terminal-progress-contract-MLXZ-i3t.mjs +905 -0
  30. package/dist/pi-tui-web-access-contract-BN8Cc_Ho.mjs +118 -0
  31. package/dist/{runtime-status-0lp9CM0V.mjs → runtime-status-Cj1nFOdS.mjs} +72 -214
  32. package/dist/session-BKGXyh80.mjs +15794 -0
  33. package/dist/{session-tdJHLnJR.mjs → session-CPt_U8_f.mjs} +10707 -3657
  34. package/dist/{startup-JaVZoTIl.mjs → startup-7BYWuvBU.mjs} +124 -8
  35. package/dist/startup.d.mts +1 -1
  36. package/dist/startup.mjs +1 -1
  37. package/dist/{client-bootstrap-F5DHFI9t.mjs → terminal-progress-source-DrqQhtT8.mjs} +3653 -2969
  38. package/dist/visual-tools.d.mts +2 -2
  39. package/dist/visual-tools.mjs +26 -31
  40. package/dist/web-preferences.d.mts +29 -0
  41. package/dist/web-preferences.mjs +15 -0
  42. package/dist/web-roster-CjqnUXNk.mjs +285 -0
  43. package/generated/dsh-presets/cordis.patch.yml +5 -3
  44. package/generated/dsh-presets/ptc.patch.yml +7 -7
  45. package/generated/dsh-presets/standard.patch.yml +6 -4
  46. package/package.json +195 -172
  47. package/dist/host-bootstrap-DAgKknbY.mjs +0 -119
  48. package/dist/performance-host-CcDJjjVA.mjs +0 -266
  49. package/dist/rolldown-runtime-8H4AJuhK.mjs +0 -14
  50. package/dist/terminal-progress-source-xor3vakJ.mjs +0 -2256
@@ -1,12 +1,11 @@
1
- import { t as __exportAll } from "./rolldown-runtime-8H4AJuhK.mjs";
2
- import { n as TUI_STARTUP_SERVICE } from "./startup-JaVZoTIl.mjs";
1
+ import { n as TUI_STARTUP_SERVICE } from "./startup-7BYWuvBU.mjs";
3
2
  import { createRequire } from "node:module";
4
3
  import * as fs from "node:fs";
5
4
  import { readFileSync } from "node:fs";
6
- import * as path from "node:path";
7
- import { dirname, isAbsolute, join } from "node:path";
8
5
  import * as os from "node:os";
9
6
  import { homedir } from "node:os";
7
+ import * as path from "node:path";
8
+ import { dirname, isAbsolute, join } from "node:path";
10
9
  import { parseCommand } from "@deepseek-ai/dsh-commands";
11
10
  import { execSync } from "node:child_process";
12
11
  import { Marked, Tokenizer } from "marked";
@@ -17,9 +16,32 @@ import { basename as basename$1, dirname as dirname$1, join as join$1 } from "pa
17
16
  import { eastAsianWidth } from "get-east-asian-width";
18
17
  import { performance as performance$1 } from "node:perf_hooks";
19
18
  import { fileURLToPath, pathToFileURL } from "node:url";
19
+ import markedCjkFriendly from "marked-cjk-friendly";
20
20
  import { EventEmitter } from "events";
21
21
  import { Service } from "@deepseek-ai/cordis";
22
22
  //#region src/domain/footer/layout.ts
23
+ /** The per-id default `Hide in TSP` value (Owner-frozen): the three items
24
+ * that a capable TSP composer already carries are hidden by default; every
25
+ * other item keeps the historical TSP behavior. This is the EDITOR default
26
+ * (a capability shortage must never turn the editor's On into Off). */
27
+ function defaultHideInTsp(id) {
28
+ return id === "permission-preset" || id === "model" || id === "reasoning";
29
+ }
30
+ /** The ONE TSP effective-visibility decision for one placement. An explicit
31
+ * user boolean always wins; otherwise the three default-On ids hide only
32
+ * when their corresponding composer control is actually available (so the
33
+ * permission state never disappears on an old client without the control),
34
+ * and every other id stays visible. */
35
+ function hideFooterRefInTsp(ref, affordances) {
36
+ if (ref.hideInTsp !== void 0) return ref.hideInTsp;
37
+ if (!defaultHideInTsp(ref.id)) return false;
38
+ switch (ref.id) {
39
+ case "permission-preset": return affordances.permission;
40
+ case "model": return affordances.model;
41
+ case "reasoning": return affordances.reasoning;
42
+ default: return false;
43
+ }
44
+ }
23
45
  /** The semantic tone vocabulary a layout may reference. */
24
46
  const TONES = /* @__PURE__ */ new Set([
25
47
  "primary",
@@ -121,6 +143,13 @@ function parseItemRef(input, index) {
121
143
  };
122
144
  ref.importance = input.importance;
123
145
  }
146
+ if (input.hideInTsp !== void 0) {
147
+ if (typeof input.hideInTsp !== "boolean") return {
148
+ kind: "error",
149
+ message: `item ${index}: hideInTsp must be a boolean`
150
+ };
151
+ ref.hideInTsp = input.hideInTsp;
152
+ }
124
153
  return ref;
125
154
  }
126
155
  function parseRow(input, index) {
@@ -245,55 +274,65 @@ function resolveCommandFooterFallback(doc) {
245
274
  }
246
275
  //#endregion
247
276
  //#region packages/pi-tui/dist/index.mjs
248
- function fuzzyMatch(query, text) {
249
- const queryLower = query.toLowerCase();
250
- const textLower = text.toLowerCase();
251
- const matchQuery = (normalizedQuery) => {
252
- if (normalizedQuery.length === 0) return {
253
- matches: true,
254
- score: 0
255
- };
256
- if (normalizedQuery.length > textLower.length) return {
257
- matches: false,
258
- score: 0
259
- };
260
- let queryIndex = 0;
261
- let score = 0;
262
- let lastMatchIndex = -1;
263
- let consecutiveMatches = 0;
264
- while (queryIndex < normalizedQuery.length) {
265
- const i = textLower.indexOf(normalizedQuery[queryIndex], lastMatchIndex + 1);
266
- if (i === -1) break;
267
- const isWordBoundary = i === 0 || /[\s\-_./:]/.test(textLower[i - 1]);
268
- if (lastMatchIndex === i - 1) {
269
- consecutiveMatches++;
270
- score -= consecutiveMatches * 5;
271
- } else {
272
- consecutiveMatches = 0;
273
- if (lastMatchIndex >= 0) score += (i - lastMatchIndex - 1) * 2;
274
- }
275
- if (isWordBoundary) score -= 10;
276
- score += i * .1;
277
- lastMatchIndex = i;
278
- queryIndex++;
277
+ function scorePositions(textLower, positions) {
278
+ let score = 0;
279
+ let lastMatchIndex = -1;
280
+ let consecutiveMatches = 0;
281
+ for (const i of positions) {
282
+ if (lastMatchIndex === i - 1) {
283
+ consecutiveMatches++;
284
+ score -= consecutiveMatches * 5;
285
+ } else {
286
+ consecutiveMatches = 0;
287
+ if (lastMatchIndex >= 0) score += (i - lastMatchIndex - 1) * 2;
279
288
  }
280
- if (queryIndex < normalizedQuery.length) return {
289
+ if (i === 0 || /[\s\-_./:]/.test(textLower[i - 1])) score -= 10;
290
+ score += i * .1;
291
+ lastMatchIndex = i;
292
+ }
293
+ return score;
294
+ }
295
+ function matchQuery(normalizedQuery, textLower) {
296
+ if (normalizedQuery.length === 0) return {
297
+ matches: true,
298
+ score: 0
299
+ };
300
+ if (normalizedQuery.length > textLower.length) return {
301
+ matches: false,
302
+ score: 0
303
+ };
304
+ const positions = [];
305
+ let lastMatchIndex = -1;
306
+ for (let queryIndex = 0; queryIndex < normalizedQuery.length; queryIndex++) {
307
+ const i = textLower.indexOf(normalizedQuery[queryIndex], lastMatchIndex + 1);
308
+ if (i === -1) return {
281
309
  matches: false,
282
310
  score: 0
283
311
  };
284
- if (normalizedQuery === textLower) score -= 100;
285
- return {
286
- matches: true,
287
- score
288
- };
312
+ positions.push(i);
313
+ lastMatchIndex = i;
314
+ }
315
+ let score = scorePositions(textLower, positions);
316
+ for (let start = textLower.indexOf(normalizedQuery); start !== -1; start = textLower.indexOf(normalizedQuery, start + 1)) {
317
+ for (let k = 0; k < positions.length; k++) positions[k] = start + k;
318
+ score = Math.min(score, scorePositions(textLower, positions));
319
+ }
320
+ if (normalizedQuery === textLower) score -= 100;
321
+ return {
322
+ matches: true,
323
+ score
289
324
  };
290
- const primaryMatch = matchQuery(queryLower);
325
+ }
326
+ function fuzzyMatch(query, text) {
327
+ const queryLower = query.toLowerCase();
328
+ const textLower = text.toLowerCase();
329
+ const primaryMatch = matchQuery(queryLower, textLower);
291
330
  if (primaryMatch.matches) return primaryMatch;
292
331
  const alphaNumericMatch = queryLower.match(/^(?<letters>[a-z]+)(?<digits>[0-9]+)$/);
293
332
  const numericAlphaMatch = queryLower.match(/^(?<digits>[0-9]+)(?<letters>[a-z]+)$/);
294
333
  const swappedQuery = alphaNumericMatch ? `${alphaNumericMatch.groups?.digits ?? ""}${alphaNumericMatch.groups?.letters ?? ""}` : numericAlphaMatch ? `${numericAlphaMatch.groups?.letters ?? ""}${numericAlphaMatch.groups?.digits ?? ""}` : "";
295
334
  if (!swappedQuery) return primaryMatch;
296
- const swappedMatch = matchQuery(swappedQuery);
335
+ const swappedMatch = matchQuery(swappedQuery, textLower);
297
336
  if (!swappedMatch.matches) return primaryMatch;
298
337
  return {
299
338
  matches: true,
@@ -540,6 +579,44 @@ function stripTerminalSequences(str) {
540
579
  }
541
580
  return result;
542
581
  }
582
+ function extractAnsiCodes(str) {
583
+ let result = "";
584
+ let i = str.indexOf("\x1B");
585
+ while (i !== -1) {
586
+ const length = ansiCodeLength(str, i);
587
+ if (length > 0) {
588
+ result += str.substring(i, i + length);
589
+ i += length;
590
+ } else i++;
591
+ i = str.indexOf("\x1B", i);
592
+ }
593
+ return result;
594
+ }
595
+ const WHITESPACE_REGEX = /\s/;
596
+ /**
597
+ * Whether a token's visible text is only whitespace. Codes closing a styled word attach to the following space,
598
+ * e.g. "\x1b[22m ", so they are skipped. Stops at the first visible non-whitespace text without allocating a
599
+ * stripped copy, because styled words reach this check on every wrap.
600
+ */
601
+ function isWhitespaceToken(token) {
602
+ let i = 0;
603
+ while (i < token.length) {
604
+ const code = token.charCodeAt(i);
605
+ if (code === 27) {
606
+ const length = ansiCodeLength(token, i);
607
+ if (length === 0) return false;
608
+ i += length;
609
+ } else if (code === 32 || code >= 9 && code <= 13) i++;
610
+ else if (code < 128 || !WHITESPACE_REGEX.test(token[i])) return false;
611
+ else i++;
612
+ }
613
+ return true;
614
+ }
615
+ const CONTROL_CHARACTERS = /[\u0000-\u001f\u007f-\u009f]+/g;
616
+ /** Replace each run of C0 and C1 control characters (ESC, BEL, newlines, ...) with one space. */
617
+ function replaceControlCharacters(str) {
618
+ return str.replace(CONTROL_CHARACTERS, " ");
619
+ }
543
620
  /** Return the terminal-cell range occupied by the grapheme at a visible column. */
544
621
  function getGraphemeCellRange(line, column) {
545
622
  let currentCol = 0;
@@ -1022,9 +1099,10 @@ function wrapSingleLine(line, width) {
1022
1099
  let currentVisibleLength = 0;
1023
1100
  for (const token of tokens) {
1024
1101
  const tokenVisibleLength = visibleWidth(token);
1025
- const isWhitespace = token.trim() === "";
1102
+ const isWhitespace = isWhitespaceToken(token);
1026
1103
  if (tokenVisibleLength > width && !isWhitespace) {
1027
1104
  if (currentLine) {
1105
+ currentLine = currentLine.trimEnd();
1028
1106
  const lineEndReset = tracker.getLineEndReset();
1029
1107
  if (lineEndReset) currentLine += lineEndReset;
1030
1108
  wrapped.push(currentLine);
@@ -1037,19 +1115,25 @@ function wrapSingleLine(line, width) {
1037
1115
  currentVisibleLength = visibleWidth(currentLine);
1038
1116
  continue;
1039
1117
  }
1040
- if (currentVisibleLength + tokenVisibleLength > width && currentVisibleLength > 0) {
1118
+ const totalNeeded = currentVisibleLength + tokenVisibleLength;
1119
+ if (totalNeeded > width && currentVisibleLength > 0) {
1041
1120
  let lineToWrap = currentLine.trimEnd();
1121
+ if (isWhitespace) {
1122
+ lineToWrap += extractAnsiCodes(token);
1123
+ updateTrackerFromText(token, tracker);
1124
+ }
1042
1125
  const lineEndReset = tracker.getLineEndReset();
1043
1126
  if (lineEndReset) lineToWrap += lineEndReset;
1044
1127
  wrapped.push(lineToWrap);
1045
1128
  if (isWhitespace) {
1046
1129
  currentLine = tracker.getActiveCodes();
1047
1130
  currentVisibleLength = 0;
1048
- } else {
1049
- currentLine = tracker.getActiveCodes() + token;
1050
- currentVisibleLength = tokenVisibleLength;
1131
+ continue;
1051
1132
  }
1052
- } else {
1133
+ currentLine = tracker.getActiveCodes() + token;
1134
+ currentVisibleLength = tokenVisibleLength;
1135
+ } else if (isWhitespace && totalNeeded > width && token.includes("\x1B")) currentLine += extractAnsiCodes(token);
1136
+ else {
1053
1137
  currentLine += token;
1054
1138
  currentVisibleLength += tokenVisibleLength;
1055
1139
  }
@@ -1312,7 +1396,7 @@ function extractSegments(line, beforeEnd, afterStart, afterLen, strictAfter = fa
1312
1396
  if (ansi) {
1313
1397
  pooledStyleTracker.process(ansi.code);
1314
1398
  if (currentCol < beforeEnd) pendingAnsiBefore += ansi.code;
1315
- else if (currentCol >= afterStart && currentCol < afterEnd && afterStarted) after += ansi.code;
1399
+ else if (currentCol >= afterStart && currentCol < afterEnd && (afterStarted || ansi.code.startsWith("\x1B_"))) after += ansi.code;
1316
1400
  i += ansi.length;
1317
1401
  continue;
1318
1402
  }
@@ -1373,14 +1457,12 @@ function escapeRegex(value) {
1373
1457
  }
1374
1458
  function buildFdPathQuery(query) {
1375
1459
  const normalized = toDisplayPath(query);
1376
- if (!normalized.includes("/")) return normalized;
1460
+ if (!normalized.includes("/")) return escapeRegex(normalized);
1377
1461
  const hasTrailingSeparator = normalized.endsWith("/");
1378
1462
  const trimmed = normalized.replace(/^\/+|\/+$/g, "");
1379
1463
  if (!trimmed) return normalized;
1380
1464
  const separatorPattern = "[\\\\/]";
1381
- const segments = trimmed.split("/").filter(Boolean).map((segment) => escapeRegex(segment));
1382
- if (segments.length === 0) return normalized;
1383
- let pattern = segments.join(separatorPattern);
1465
+ let pattern = trimmed.split("/").filter(Boolean).map((segment) => escapeRegex(segment)).join(separatorPattern);
1384
1466
  if (hasTrailingSeparator) pattern += separatorPattern;
1385
1467
  return pattern;
1386
1468
  }
@@ -2008,6 +2090,13 @@ const SYMBOL_KEYS = /* @__PURE__ */ new Set([
2008
2090
  ">",
2009
2091
  "?"
2010
2092
  ]);
2093
+ const SHIFTED_SYMBOL_KEYS = /* @__PURE__ */ new Set("~!@#$%^&*()_+|{}:<>?");
2094
+ const MODIFIER_NAMES = [
2095
+ "shift",
2096
+ "alt",
2097
+ "ctrl",
2098
+ "super"
2099
+ ];
2011
2100
  const MODIFIERS = {
2012
2101
  shift: 1,
2013
2102
  alt: 2,
@@ -2035,8 +2124,22 @@ const FUNCTIONAL_CODEPOINTS = {
2035
2124
  pageUp: -12,
2036
2125
  pageDown: -13,
2037
2126
  home: -14,
2038
- end: -15
2127
+ end: -15,
2128
+ f1: -21,
2129
+ f2: -22,
2130
+ f3: -23,
2131
+ f4: -24,
2132
+ f5: -25,
2133
+ f6: -26,
2134
+ f7: -27,
2135
+ f8: -28,
2136
+ f9: -29,
2137
+ f10: -30,
2138
+ f11: -31,
2139
+ f12: -32
2039
2140
  };
2141
+ const KITTY_FUNCTIONAL_PUA_START = 57344;
2142
+ const KITTY_FUNCTIONAL_PUA_END = 63743;
2040
2143
  const KITTY_FUNCTIONAL_KEY_EQUIVALENTS = /* @__PURE__ */ new Map([
2041
2144
  [57399, 48],
2042
2145
  [57400, 49],
@@ -2073,6 +2176,15 @@ function normalizeShiftedLetterIdentityCodepoint(codepoint, modifier) {
2073
2176
  if ((modifier & -193 & MODIFIERS.shift) !== 0 && codepoint >= 65 && codepoint <= 90) return codepoint + 32;
2074
2177
  return codepoint;
2075
2178
  }
2179
+ function getLogicalShiftedSymbolCandidate(codepoint, modifier, allowedSymbols) {
2180
+ if (codepoint === void 0 || (modifier & MODIFIERS.shift) === 0) return void 0;
2181
+ const normalizedCodepoint = normalizeKittyFunctionalCodepoint(codepoint);
2182
+ if (!allowedSymbols.has(String.fromCharCode(normalizedCodepoint))) return void 0;
2183
+ return {
2184
+ codepoint: normalizedCodepoint,
2185
+ modifier: modifier & ~MODIFIERS.shift
2186
+ };
2187
+ }
2076
2188
  const LEGACY_KEY_SEQUENCES = {
2077
2189
  up: ["\x1B[A", "\x1BOA"],
2078
2190
  down: ["\x1B[B", "\x1BOB"],
@@ -2216,7 +2328,7 @@ const matchesLegacyModifierSequence = (data, key, modifier) => {
2216
2328
  if (modifier === MODIFIERS.ctrl) return matchesLegacySequence(data, LEGACY_CTRL_SEQUENCES[key]);
2217
2329
  return false;
2218
2330
  };
2219
- const KITTY_EVENT_SEQUENCE = /^\x1b\[\d+(?::\d*)?(?::\d+)?;\d+:(?<event>[23])(?:u|~|[ABCDHF])$/u;
2331
+ const KITTY_EVENT_SEQUENCE = /^\x1b\[\d+(?::\d*)?(?::\d+)?;\d+:(?<event>[23])(?:u|~|[ABCDHFPQS])$/u;
2220
2332
  function kittyEventType(data) {
2221
2333
  const match = KITTY_EVENT_SEQUENCE.exec(data);
2222
2334
  if (match === null) return void 0;
@@ -2285,7 +2397,19 @@ function parseKittySequence(data) {
2285
2397
  5: FUNCTIONAL_CODEPOINTS.pageUp,
2286
2398
  6: FUNCTIONAL_CODEPOINTS.pageDown,
2287
2399
  7: FUNCTIONAL_CODEPOINTS.home,
2288
- 8: FUNCTIONAL_CODEPOINTS.end
2400
+ 8: FUNCTIONAL_CODEPOINTS.end,
2401
+ 11: FUNCTIONAL_CODEPOINTS.f1,
2402
+ 12: FUNCTIONAL_CODEPOINTS.f2,
2403
+ 13: FUNCTIONAL_CODEPOINTS.f3,
2404
+ 14: FUNCTIONAL_CODEPOINTS.f4,
2405
+ 15: FUNCTIONAL_CODEPOINTS.f5,
2406
+ 17: FUNCTIONAL_CODEPOINTS.f6,
2407
+ 18: FUNCTIONAL_CODEPOINTS.f7,
2408
+ 19: FUNCTIONAL_CODEPOINTS.f8,
2409
+ 20: FUNCTIONAL_CODEPOINTS.f9,
2410
+ 21: FUNCTIONAL_CODEPOINTS.f10,
2411
+ 23: FUNCTIONAL_CODEPOINTS.f11,
2412
+ 24: FUNCTIONAL_CODEPOINTS.f12
2289
2413
  }[keyNum];
2290
2414
  if (codepoint !== void 0) return {
2291
2415
  codepoint,
@@ -2303,14 +2427,33 @@ function parseKittySequence(data) {
2303
2427
  eventType
2304
2428
  };
2305
2429
  }
2430
+ const fKeyMatch = data.match(/^\x1b\[(?:1;(\d+)(?::(\d+))?)?([PQS])$/);
2431
+ if (fKeyMatch) {
2432
+ const modValue = fKeyMatch[1] ? parseInt(fKeyMatch[1], 10) : 1;
2433
+ const eventType = parseEventType(fKeyMatch[2]);
2434
+ return {
2435
+ codepoint: {
2436
+ P: FUNCTIONAL_CODEPOINTS.f1,
2437
+ Q: FUNCTIONAL_CODEPOINTS.f2,
2438
+ S: FUNCTIONAL_CODEPOINTS.f4
2439
+ }[fKeyMatch[3]],
2440
+ modifier: modValue - 1,
2441
+ eventType
2442
+ };
2443
+ }
2306
2444
  return null;
2307
2445
  }
2308
2446
  function matchesKittySequence(data, expectedCodepoint, expectedModifier) {
2309
2447
  const parsed = parseKittySequence(data);
2310
2448
  if (!parsed) return false;
2311
- if ((parsed.modifier & -193) !== (expectedModifier & -193)) return false;
2449
+ const actualMod = parsed.modifier & -193;
2450
+ const expectedMod = expectedModifier & -193;
2312
2451
  const normalizedCodepoint = normalizeShiftedLetterIdentityCodepoint(normalizeKittyFunctionalCodepoint(parsed.codepoint), parsed.modifier);
2313
- if (normalizedCodepoint === normalizeShiftedLetterIdentityCodepoint(normalizeKittyFunctionalCodepoint(expectedCodepoint), expectedModifier)) return true;
2452
+ const normalizedExpectedCodepoint = normalizeShiftedLetterIdentityCodepoint(normalizeKittyFunctionalCodepoint(expectedCodepoint), expectedModifier);
2453
+ if (actualMod === expectedMod && normalizedCodepoint === normalizedExpectedCodepoint) return true;
2454
+ const logicalShiftedSymbol = getLogicalShiftedSymbolCandidate(parsed.shiftedKey, actualMod, SYMBOL_KEYS);
2455
+ if (logicalShiftedSymbol && (logicalShiftedSymbol.modifier & -193) === expectedMod && logicalShiftedSymbol.codepoint === normalizeKittyFunctionalCodepoint(expectedCodepoint)) return true;
2456
+ if (actualMod !== expectedMod) return false;
2314
2457
  if (parsed.baseLayoutKey !== void 0 && parsed.baseLayoutKey === expectedCodepoint) {
2315
2458
  const cp = normalizedCodepoint;
2316
2459
  const isLatinLetter = cp >= 97 && cp <= 122;
@@ -2375,10 +2518,11 @@ function isDigitKey(key) {
2375
2518
  return key >= "0" && key <= "9";
2376
2519
  }
2377
2520
  function matchesPrintableModifyOtherKeys(data, expectedKeycode, expectedModifier) {
2378
- if (expectedModifier === 0) return false;
2379
2521
  const parsed = parseModifyOtherKeysSequence(data);
2380
- if (!parsed || parsed.modifier !== expectedModifier) return false;
2381
- return normalizeShiftedLetterIdentityCodepoint(parsed.codepoint, parsed.modifier) === normalizeShiftedLetterIdentityCodepoint(expectedKeycode, expectedModifier);
2522
+ if (!parsed) return false;
2523
+ if (parsed.modifier === expectedModifier && normalizeShiftedLetterIdentityCodepoint(parsed.codepoint, parsed.modifier) === normalizeShiftedLetterIdentityCodepoint(expectedKeycode, expectedModifier)) return true;
2524
+ const logicalShiftedSymbol = getLogicalShiftedSymbolCandidate(parsed.codepoint, parsed.modifier, SHIFTED_SYMBOL_KEYS);
2525
+ return logicalShiftedSymbol?.modifier === expectedModifier && logicalShiftedSymbol.codepoint === expectedKeycode;
2382
2526
  }
2383
2527
  function formatKeyNameWithModifiers(keyName, modifier) {
2384
2528
  const mods = [];
@@ -2391,15 +2535,22 @@ function formatKeyNameWithModifiers(keyName, modifier) {
2391
2535
  return mods.length > 0 ? `${mods.join("+")}+${keyName}` : keyName;
2392
2536
  }
2393
2537
  function parseKeyId(keyId) {
2394
- const parts = keyId.toLowerCase().split("+");
2395
- const key = parts[parts.length - 1];
2396
- if (!key) return null;
2538
+ let key = keyId.toLowerCase();
2539
+ const modifiers = /* @__PURE__ */ new Set();
2540
+ while (true) {
2541
+ const modifier = MODIFIER_NAMES.find((name) => key.startsWith(`${name}+`));
2542
+ if (!modifier) break;
2543
+ if (modifiers.has(modifier)) return null;
2544
+ modifiers.add(modifier);
2545
+ key = key.slice(modifier.length + 1);
2546
+ }
2547
+ if (!key || key.includes("+") && key !== "+") return null;
2397
2548
  return {
2398
2549
  key,
2399
- ctrl: parts.includes("ctrl"),
2400
- shift: parts.includes("shift"),
2401
- alt: parts.includes("alt"),
2402
- super: parts.includes("super")
2550
+ ctrl: modifiers.has("ctrl"),
2551
+ shift: modifiers.has("shift"),
2552
+ alt: modifiers.has("alt"),
2553
+ super: modifiers.has("super")
2403
2554
  };
2404
2555
  }
2405
2556
  /**
@@ -2531,9 +2682,11 @@ function matchesKey(data, keyId) {
2531
2682
  case "f9":
2532
2683
  case "f10":
2533
2684
  case "f11":
2534
- case "f12":
2535
- if (modifier !== 0) return false;
2536
- return matchesLegacySequence(data, LEGACY_KEY_SEQUENCES[key]);
2685
+ case "f12": {
2686
+ const functionKey = key;
2687
+ if (modifier === 0 && matchesLegacySequence(data, LEGACY_KEY_SEQUENCES[functionKey])) return true;
2688
+ return matchesKittySequence(data, FUNCTIONAL_CODEPOINTS[functionKey], modifier);
2689
+ }
2537
2690
  }
2538
2691
  if (key.length === 1 && (key >= "a" && key <= "z" || isDigitKey(key) || SYMBOL_KEYS.has(key))) {
2539
2692
  const codepoint = key.charCodeAt(0);
@@ -2556,7 +2709,7 @@ function matchesKey(data, keyId) {
2556
2709
  return matchesKittySequence(data, codepoint, MODIFIERS.shift) || matchesPrintableModifyOtherKeys(data, codepoint, MODIFIERS.shift);
2557
2710
  }
2558
2711
  if (modifier !== 0) return matchesKittySequence(data, codepoint, modifier) || matchesPrintableModifyOtherKeys(data, codepoint, modifier);
2559
- return data === key || matchesKittySequence(data, codepoint, 0);
2712
+ return data === key || matchesKittySequence(data, codepoint, 0) || matchesPrintableModifyOtherKeys(data, codepoint, 0);
2560
2713
  }
2561
2714
  return false;
2562
2715
  }
@@ -2584,6 +2737,7 @@ function formatParsedKey(codepoint, modifier, baseLayoutKey) {
2584
2737
  else if (effectiveCodepoint === FUNCTIONAL_CODEPOINTS.end) keyName = "end";
2585
2738
  else if (effectiveCodepoint === FUNCTIONAL_CODEPOINTS.pageUp) keyName = "pageUp";
2586
2739
  else if (effectiveCodepoint === FUNCTIONAL_CODEPOINTS.pageDown) keyName = "pageDown";
2740
+ else if (effectiveCodepoint <= FUNCTIONAL_CODEPOINTS.f1 && effectiveCodepoint >= FUNCTIONAL_CODEPOINTS.f12) keyName = `f${FUNCTIONAL_CODEPOINTS.f1 - effectiveCodepoint + 1}`;
2587
2741
  else if (effectiveCodepoint === ARROW_CODEPOINTS.up) keyName = "up";
2588
2742
  else if (effectiveCodepoint === ARROW_CODEPOINTS.down) keyName = "down";
2589
2743
  else if (effectiveCodepoint === ARROW_CODEPOINTS.left) keyName = "left";
@@ -2596,9 +2750,15 @@ function formatParsedKey(codepoint, modifier, baseLayoutKey) {
2596
2750
  }
2597
2751
  function parseKey(data) {
2598
2752
  const kitty = parseKittySequence(data);
2599
- if (kitty) return formatParsedKey(kitty.codepoint, kitty.modifier, kitty.baseLayoutKey);
2753
+ if (kitty) {
2754
+ const logicalShiftedSymbol = getLogicalShiftedSymbolCandidate(kitty.shiftedKey, kitty.modifier, SYMBOL_KEYS);
2755
+ return formatParsedKey(logicalShiftedSymbol?.codepoint ?? kitty.codepoint, logicalShiftedSymbol?.modifier ?? kitty.modifier, kitty.baseLayoutKey);
2756
+ }
2600
2757
  const modifyOtherKeys = parseModifyOtherKeysSequence(data);
2601
- if (modifyOtherKeys) return formatParsedKey(modifyOtherKeys.codepoint, modifyOtherKeys.modifier);
2758
+ if (modifyOtherKeys) {
2759
+ const logicalShiftedSymbol = getLogicalShiftedSymbolCandidate(modifyOtherKeys.codepoint, modifyOtherKeys.modifier, SHIFTED_SYMBOL_KEYS);
2760
+ return formatParsedKey(logicalShiftedSymbol?.codepoint ?? modifyOtherKeys.codepoint, logicalShiftedSymbol?.modifier ?? modifyOtherKeys.modifier);
2761
+ }
2602
2762
  if (_kittyProtocolActive) {
2603
2763
  if (data === "\x1B\r" || data === "\n") return "shift+enter";
2604
2764
  }
@@ -2675,6 +2835,7 @@ function decodeKittyPrintable(data) {
2675
2835
  if (modifier & MODIFIERS.shift && typeof shiftedKey === "number") effectiveCodepoint = shiftedKey;
2676
2836
  effectiveCodepoint = normalizeKittyFunctionalCodepoint(effectiveCodepoint);
2677
2837
  if (!Number.isFinite(effectiveCodepoint) || effectiveCodepoint < 32) return void 0;
2838
+ if (effectiveCodepoint >= KITTY_FUNCTIONAL_PUA_START && effectiveCodepoint <= KITTY_FUNCTIONAL_PUA_END) return;
2678
2839
  try {
2679
2840
  return String.fromCodePoint(effectiveCodepoint);
2680
2841
  } catch {
@@ -2806,10 +2967,20 @@ function detectCapabilitiesFromEnvironment(tmuxForwardsHyperlink) {
2806
2967
  hyperlinks: false
2807
2968
  };
2808
2969
  if (termProgram === "herdr") return {
2809
- images: null,
2970
+ images: "kitty",
2810
2971
  trueColor: hasTrueColorHint,
2811
2972
  hyperlinks: true
2812
2973
  };
2974
+ if (termProgram === "rex") return {
2975
+ images: "kitty",
2976
+ trueColor: true,
2977
+ hyperlinks: true
2978
+ };
2979
+ if (termProgram === "orca" && process.env.ORCA_IMAGE_PROTOCOL === "kitty") return {
2980
+ images: "kitty",
2981
+ trueColor: true,
2982
+ hyperlinks: true
2983
+ };
2813
2984
  if (process.env.KITTY_WINDOW_ID || termProgram === "kitty" || termProgram === "tern") return {
2814
2985
  images: "kitty",
2815
2986
  trueColor: true,
@@ -3054,8 +3225,10 @@ function encodeITerm2(base64Data, options = {}) {
3054
3225
  }
3055
3226
  const kittyImageMetadata = /* @__PURE__ */ new Map();
3056
3227
  let kittyTransmissionGeneration = 0;
3228
+ let maxKittyImageRows = 0;
3057
3229
  function registerKittyImageMetadata(metadata) {
3058
3230
  kittyTransmissionGeneration += 1;
3231
+ maxKittyImageRows = Math.max(maxKittyImageRows, metadata.rows);
3059
3232
  kittyImageMetadata.delete(metadata.imageId);
3060
3233
  kittyImageMetadata.set(metadata.imageId, {
3061
3234
  ...metadata,
@@ -3066,6 +3239,10 @@ function registerKittyImageMetadata(metadata) {
3066
3239
  if (oldestImageId !== void 0) kittyImageMetadata.delete(oldestImageId);
3067
3240
  }
3068
3241
  }
3242
+ /** Return the row height of the tallest Kitty image registered so far. */
3243
+ function getMaxKittyImageRows() {
3244
+ return maxKittyImageRows;
3245
+ }
3069
3246
  function getRegisteredKittyImageMetadataFromControls(controls) {
3070
3247
  const imageId = /(?:^|,)i=(\d+)(?:,|$)/.exec(controls)?.[1];
3071
3248
  return imageId === void 0 ? void 0 : kittyImageMetadata.get(Number.parseInt(imageId, 10));
@@ -3482,6 +3659,14 @@ function isFocusable(component) {
3482
3659
  * TUI finds and strips this marker, then positions the hardware cursor there.
3483
3660
  */
3484
3661
  const CURSOR_MARKER = "\x1B_pi:c\x07";
3662
+ /** Fake cursor markers - zero-width APC sequences around the text drawn as the cursor. See resolveFakeCursors(). */
3663
+ const FAKE_CURSOR_START = "\x1B_pi:fc\x07";
3664
+ const FAKE_CURSOR_END = "\x1B_pi:/fc\x07";
3665
+ const FOCUSED_FAKE_CURSOR = /(\x1b_pi:c\x07)\x1b_pi:fc\x07(.*?)(?:\x1b_pi:\/fc\x07|$)/s;
3666
+ /** Wrap text in fake cursor markers. */
3667
+ function renderFakeCursor(text) {
3668
+ return `${FAKE_CURSOR_START}${text}${FAKE_CURSOR_END}`;
3669
+ }
3485
3670
  /** Parse a SizeValue into absolute value given a reference size */
3486
3671
  function parseSizeValue(value, referenceSize) {
3487
3672
  if (value === void 0) return void 0;
@@ -3797,17 +3982,88 @@ var TuiBase = class TuiBase extends Container {
3797
3982
  return component.mouseLayout;
3798
3983
  }
3799
3984
  overlayFocusRestore = { status: "inactive" };
3800
- constructor(terminal, showHardwareCursor, logDirectory) {
3985
+ /**
3986
+ * The Client-local SIXEL trust port (X072), or undefined for every other
3987
+ * terminal. A Screen never parses a DCS itself: it asks this port, which
3988
+ * only recognizes rasters its own owner encoded.
3989
+ */
3990
+ sixelScreen;
3991
+ /** Whether `start()` has brought the terminal up (only then may a query go out). */
3992
+ terminalStarted = false;
3993
+ /** Observers of this screen's ONE real `CSI 6;h;w t` parse (X072). */
3994
+ cellSizeListeners = /* @__PURE__ */ new Set();
3995
+ constructor(terminal, showHardwareCursor, logDirectory, sixelScreen) {
3801
3996
  super();
3802
3997
  this.terminal = terminal;
3803
3998
  this.logDirectory = logDirectory;
3999
+ this.sixelScreen = sixelScreen;
3804
4000
  if (showHardwareCursor !== void 0) this.showHardwareCursor = showHardwareCursor;
3805
4001
  }
4002
+ /**
4003
+ * Whether this line must be treated as an IMAGE by the physical Screen
4004
+ * (X072): a legacy Kitty/iTerm2 placement, or an exact DCS the Client-local
4005
+ * SIXEL owner registered.
4006
+ *
4007
+ * This is a trust question, not a syntax question. A DCS that is not in the
4008
+ * owner's registry stays ordinary text and goes through the normal
4009
+ * normalization/truncation path, so an arbitrary `ESC P…q…ESC \` from a tool
4010
+ * result can never be promoted to a device command.
4011
+ */
4012
+ isRenderableImageLine(line) {
4013
+ return isImageLine(line) || this.sixelScreen?.footprint(line) !== void 0 || this.sixelScreen?.candidate(line) !== void 0;
4014
+ }
4015
+ /** The registered SIXEL footprint of a trusted anchor line, if any (X072). */
4016
+ sixelFootprint(line) {
4017
+ return this.sixelScreen?.footprint(line);
4018
+ }
4019
+ /**
4020
+ * Observe every real cell-size reply this screen parses, or return the
4021
+ * current value immediately when it is already known (X072).
4022
+ *
4023
+ * There is ONE parser (`consumeCellSizeResponse`); observers never see a
4024
+ * query they issued, only the terminal's actual `CSI 6;h;w t` answer.
4025
+ */
4026
+ onCellSizeObserved(listener) {
4027
+ this.cellSizeListeners.add(listener);
4028
+ return () => {
4029
+ this.cellSizeListeners.delete(listener);
4030
+ };
4031
+ }
4032
+ /**
4033
+ * Ask the terminal for its cell size in device pixels (`CSI 16t`, answered as
4034
+ * `CSI 6;h;w t`) on behalf of a consumer that needs REAL geometry (X072).
4035
+ *
4036
+ * Unlike the startup probe this refuses before `start()`: a query written to
4037
+ * a terminal this screen does not own yet would be answered into the input
4038
+ * stream of whoever does.
4039
+ */
4040
+ queryCellSizeForSixel() {
4041
+ if (!this.terminalStarted) return;
4042
+ this.terminal.write("\x1B[16t");
4043
+ }
3806
4044
  resetRenderState() {}
3807
4045
  beforeTerminalStart() {}
3808
4046
  afterTerminalStart() {}
3809
4047
  beforeTerminalStop(_options) {}
3810
4048
  afterTerminalStop(_options) {}
4049
+ /** Mode resets written before the terminal's own resets when the process exits without stop(). */
4050
+ getExitRestorePrefix() {
4051
+ return `${this.terminalColorSchemeNotificationsEnabled ? "\x1B[?2031l" : ""}\x1b[?25h`;
4052
+ }
4053
+ /** Mode resets written after the terminal's own resets when the process exits without stop(). */
4054
+ getExitRestoreSuffix() {
4055
+ return "";
4056
+ }
4057
+ /**
4058
+ * Last-resort restore for exit paths that skip stop(), e.g. a direct process.exit() (#11170).
4059
+ * Hard kills and native aborts run no JavaScript and cannot be covered.
4060
+ */
4061
+ exitRestoreHandler = () => {
4062
+ if (this.stopped) return;
4063
+ try {
4064
+ this.terminal.restoreOnExit?.(this.getExitRestorePrefix(), this.getExitRestoreSuffix());
4065
+ } catch {}
4066
+ };
3811
4067
  get fullRedraws() {
3812
4068
  return this.fullRedrawCount;
3813
4069
  }
@@ -4147,8 +4403,11 @@ var TuiBase = class TuiBase extends Container {
4147
4403
  }
4148
4404
  start() {
4149
4405
  this.stopped = false;
4406
+ process.off("exit", this.exitRestoreHandler);
4407
+ process.on("exit", this.exitRestoreHandler);
4150
4408
  this.beforeTerminalStart();
4151
4409
  this.terminal.start((data) => this.handleTerminalInput(data), () => this.requestRender());
4410
+ this.terminalStarted = true;
4152
4411
  this.afterTerminalStart();
4153
4412
  this.terminal.hideCursor();
4154
4413
  if (this.terminalColorSchemeNotificationsEnabled) this.terminal.write("\x1B[?2031h");
@@ -4181,6 +4440,8 @@ var TuiBase = class TuiBase extends Container {
4181
4440
  }
4182
4441
  stop(options = {}) {
4183
4442
  this.stopped = true;
4443
+ process.off("exit", this.exitRestoreHandler);
4444
+ this.terminalStarted = false;
4184
4445
  this.cancelRenderTimer();
4185
4446
  this.settleBackgroundProbe(void 0);
4186
4447
  const failures = [];
@@ -4363,6 +4624,10 @@ var TuiBase = class TuiBase extends Container {
4363
4624
  widthPx,
4364
4625
  heightPx
4365
4626
  });
4627
+ for (const listener of this.cellSizeListeners) listener({
4628
+ widthPx,
4629
+ heightPx
4630
+ });
4366
4631
  this.invalidate();
4367
4632
  this.requestRender();
4368
4633
  return true;
@@ -4471,7 +4736,7 @@ var TuiBase = class TuiBase extends Container {
4471
4736
  for (const entry of visibleEntries) {
4472
4737
  const { component, options } = entry;
4473
4738
  const { width, maxHeight } = this.resolveOverlayLayout(options, 0, termWidth, termHeight);
4474
- let overlayLines = component.render(width);
4739
+ let overlayLines = this.resolveFakeCursors(component.render(width));
4475
4740
  if (maxHeight !== void 0 && overlayLines.length > maxHeight) overlayLines = overlayLines.slice(0, maxHeight);
4476
4741
  const { row, col } = this.resolveOverlayLayout(options, overlayLines.length, termWidth, termHeight);
4477
4742
  entry.bounds = {
@@ -4512,14 +4777,38 @@ var TuiBase = class TuiBase extends Container {
4512
4777
  const reset = SEGMENT_RESET;
4513
4778
  for (let i = 0; i < lines.length; i++) {
4514
4779
  const line = lines[i];
4515
- if (!isImageLine(line)) lines[i] = normalizeTerminalOutput(line) + reset;
4780
+ if (!this.isRenderableImageLine(line)) lines[i] = normalizeTerminalOutput(line) + reset;
4516
4781
  }
4517
4782
  return lines;
4518
4783
  }
4519
4784
  compositeLineAt(baseLine, overlayLine, startCol, overlayWidth, totalWidth) {
4785
+ if (this.sixelScreen?.footprint(baseLine) !== void 0 || this.sixelScreen?.candidate(baseLine) !== void 0) return compositeTuiLine("", overlayLine, startCol, overlayWidth, totalWidth);
4520
4786
  return compositeTuiLine(baseLine, overlayLine, startCol, overlayWidth, totalWidth);
4521
4787
  }
4522
4788
  /**
4789
+ * The absolute line range a visible overlay painted on this frame (X072).
4790
+ *
4791
+ * Overlay placements are viewport-relative, exactly like the compositor's own
4792
+ * `workingHeight - termHeight` origin, so the mapping is derived from the same
4793
+ * inputs instead of being guessed by the caller.
4794
+ */
4795
+ overlayPaintedLineRange(overlayRow, overlayHeight, totalLines) {
4796
+ const first = Math.max(0, totalLines - this.terminal.rows) + overlayRow;
4797
+ return {
4798
+ first,
4799
+ last: first + overlayHeight - 1
4800
+ };
4801
+ }
4802
+ /** Whether a visible overlay painted any cell on any of these absolute lines. */
4803
+ linesCoveredByOverlay(firstLine, lastLine, totalLines) {
4804
+ for (const layout of this.renderedOverlayLayouts) {
4805
+ const range = this.overlayPaintedLineRange(layout.row, layout.height, totalLines);
4806
+ if (range.last < firstLine || range.first > lastLine) continue;
4807
+ return true;
4808
+ }
4809
+ return false;
4810
+ }
4811
+ /**
4523
4812
  * Find and extract cursor position from rendered lines.
4524
4813
  * Searches for CURSOR_MARKER, calculates its position, and strips it from the output.
4525
4814
  * Only scans the bottom terminal height lines (visible viewport).
@@ -4544,6 +4833,17 @@ var TuiBase = class TuiBase extends Container {
4544
4833
  return null;
4545
4834
  }
4546
4835
  /**
4836
+ * Resolve fake cursor markers to reverse video. When the hardware cursor is shown, a fake cursor
4837
+ * directly after CURSOR_MARKER is dropped because the terminal cursor is drawn there. Fake cursors
4838
+ * of components without focus have no CURSOR_MARKER and stay visible.
4839
+ */
4840
+ resolveFakeCursors(lines) {
4841
+ return lines.map((line) => {
4842
+ if (!line.includes("\x1B_pi:fc\x07")) return line;
4843
+ return (this.showHardwareCursor ? line.replace(FOCUSED_FAKE_CURSOR, "$1$2") : line).replaceAll(FAKE_CURSOR_START, "\x1B[7m").replaceAll(FAKE_CURSOR_END, "\x1B[27m");
4844
+ });
4845
+ }
4846
+ /**
4547
4847
  * Query the terminal's theme colors: the default foreground (OSC 10), the default background
4548
4848
  * (OSC 11), and ANSI colors 0-15 (OSC 4), followed by a DA1 request that marks the end of the
4549
4849
  * replies. Resolves when the DA1 reply or all color replies arrive, or when the timeout expires.
@@ -4901,6 +5201,18 @@ function getKeybindings() {
4901
5201
  return globalKeybindings;
4902
5202
  }
4903
5203
  /**
5204
+ * Returns the selection index after a `tui.select.pageUp` or `tui.select.pageDown` key, moved by `pageSize` and
5205
+ * clamped to `0..itemCount - 1`. Returns undefined when `data` is not a selection page key, and 0 for a page key on
5206
+ * an empty list, so callers must still check that the list has items before selecting.
5207
+ */
5208
+ function getSelectPageIndex(keybindings, data, selectedIndex, itemCount, pageSize) {
5209
+ let direction;
5210
+ if (keybindings.matches(data, "tui.select.pageUp")) direction = -1;
5211
+ else if (keybindings.matches(data, "tui.select.pageDown")) direction = 1;
5212
+ else return void 0;
5213
+ return Math.max(0, Math.min(itemCount - 1, selectedIndex + direction * pageSize));
5214
+ }
5215
+ /**
4904
5216
  * Text component - displays multi-line text with word wrapping
4905
5217
  */
4906
5218
  var Text = class {
@@ -4918,6 +5230,7 @@ var Text = class {
4918
5230
  this.customBgFn = customBgFn;
4919
5231
  }
4920
5232
  setText(text) {
5233
+ if (text === this.text) return;
4921
5234
  this.text = text;
4922
5235
  this.cachedText = void 0;
4923
5236
  this.cachedWidth = void 0;
@@ -5122,6 +5435,7 @@ const MIN_DESCRIPTION_WIDTH = 10;
5122
5435
  const normalizeToSingleLine = (text) => text.replace(/[\r\n]+/g, " ").trim();
5123
5436
  const clamp = (value, min, max) => Math.max(min, Math.min(value, max));
5124
5437
  var SelectList = class {
5438
+ capturesViewportInput = true;
5125
5439
  items = [];
5126
5440
  filteredItems = [];
5127
5441
  selectedIndex = 0;
@@ -5222,12 +5536,17 @@ var SelectList = class {
5222
5536
  }
5223
5537
  handleInput(keyData) {
5224
5538
  const kb = getKeybindings();
5539
+ const pageIndex = getSelectPageIndex(kb, keyData, this.selectedIndex, this.filteredItems.length, this.maxVisible);
5225
5540
  if (kb.matches(keyData, "tui.select.up")) {
5226
5541
  this.selectedIndex = this.selectedIndex === 0 ? this.filteredItems.length - 1 : this.selectedIndex - 1;
5227
5542
  this.notifySelectionChange();
5228
5543
  } else if (kb.matches(keyData, "tui.select.down")) {
5229
5544
  this.selectedIndex = this.selectedIndex === this.filteredItems.length - 1 ? 0 : this.selectedIndex + 1;
5230
5545
  this.notifySelectionChange();
5546
+ } else if (pageIndex !== void 0) {
5547
+ if (this.filteredItems.length === 0 || pageIndex === this.selectedIndex) return;
5548
+ this.selectedIndex = pageIndex;
5549
+ this.notifySelectionChange();
5231
5550
  } else if (kb.matches(keyData, "tui.select.confirm")) {
5232
5551
  const selectedItem = this.filteredItems[this.selectedIndex];
5233
5552
  if (selectedItem && this.onSelect) this.onSelect(selectedItem);
@@ -5510,6 +5829,10 @@ var Editor = class Editor {
5510
5829
  };
5511
5830
  /** Focusable interface - set by TUI when focus changes */
5512
5831
  focused = false;
5832
+ /** The open autocomplete menu receives fullscreen viewport keys, such as PageUp/PageDown. */
5833
+ get capturesViewportInput() {
5834
+ return this.autocompleteState !== null;
5835
+ }
5513
5836
  tui;
5514
5837
  theme;
5515
5838
  paddingX = 0;
@@ -5580,6 +5903,15 @@ var Editor = class Editor {
5580
5903
  * unchanged body never needs another scan (X064). */
5581
5904
  pasteImagePlaceholders = /* @__PURE__ */ new Map();
5582
5905
  onSubmit;
5906
+ /** Pre-clear submit ADMISSION (dsh-pi-tui divergence X075): called with
5907
+ * the expanded submitted value BEFORE {@link onBeforeSubmitClear} and
5908
+ * before any draft/undo/paste-registry mutation. Returning `false` (or
5909
+ * throwing) aborts THIS submit gesture as if it never started: the draft,
5910
+ * caret, paste registry and Undo history stay exactly as they were, and
5911
+ * no history row/ack/business dispatch happens. The host uses it for the
5912
+ * one refusal that cannot be expressed after the clear: a terminal
5913
+ * pasted image path whose attachment read is still in flight. */
5914
+ onMaySubmit;
5583
5915
  /** Called with the submitted text immediately BEFORE the draft/undo clear.
5584
5916
  * The host reserves submission-time resources first and returns a ONE-SHOT
5585
5917
  * release: it runs in a finally after the synchronous clear + onSubmit
@@ -5834,10 +6166,11 @@ var Editor = class Editor {
5834
6166
  if (after.length > 0) {
5835
6167
  const firstGrapheme = [...this.segment(after, "grapheme")][0]?.segment || "";
5836
6168
  const restAfter = after.slice(firstGrapheme.length);
5837
- const cursor = `\x1b[7m${firstGrapheme}\x1b[0m`;
6169
+ const cursor = renderFakeCursor(firstGrapheme);
5838
6170
  displayText = before + marker + cursor + restAfter;
5839
6171
  } else {
5840
- displayText = before + marker + "\x1B[7m \x1B[0m";
6172
+ const cursor = renderFakeCursor(" ");
6173
+ displayText = before + marker + cursor;
5841
6174
  lineVisibleWidth = lineVisibleWidth + 1;
5842
6175
  if (lineVisibleWidth > contentWidth && paddingX > 0) cursorInPadding = true;
5843
6176
  }
@@ -5986,7 +6319,7 @@ var Editor = class Editor {
5986
6319
  this.cancelAutocomplete();
5987
6320
  return;
5988
6321
  }
5989
- if (kb.matches(data, "tui.select.up") || kb.matches(data, "tui.select.down")) {
6322
+ if (kb.matches(data, "tui.select.up") || kb.matches(data, "tui.select.down") || kb.matches(data, "tui.select.pageUp") || kb.matches(data, "tui.select.pageDown")) {
5990
6323
  this.autocompleteList.handleInput(data);
5991
6324
  return;
5992
6325
  }
@@ -6523,6 +6856,7 @@ var Editor = class Editor {
6523
6856
  }
6524
6857
  submitValue() {
6525
6858
  const result = this.expandPasteMarkersSinglePass(this.state.lines.join("\n")).text.trim();
6859
+ if (this.onMaySubmit?.(result) === false) return;
6526
6860
  const release = this.onBeforeSubmitClear?.(result);
6527
6861
  try {
6528
6862
  this.clearDraftAfterSubmit();
@@ -7988,7 +8322,7 @@ var Input = class {
7988
8322
  const placeholder = truncateToWidth(this.placeholder, availableWidth, "");
7989
8323
  const atCursor = [...segmenter$1.segment(placeholder)][0]?.segment ?? " ";
7990
8324
  const afterCursor = placeholder.slice(atCursor.length);
7991
- const textWithCursor = (this.focused ? CURSOR_MARKER : "") + `\x1b[7m${this.placeholderStyle(atCursor)}\x1b[27m` + this.placeholderStyle(afterCursor);
8325
+ const textWithCursor = (this.focused ? CURSOR_MARKER : "") + renderFakeCursor(this.placeholderStyle(atCursor)) + this.placeholderStyle(afterCursor);
7992
8326
  const padding = " ".repeat(Math.max(0, availableWidth - visibleWidth(textWithCursor)));
7993
8327
  return [this.prompt + textWithCursor + padding];
7994
8328
  }
@@ -8019,7 +8353,7 @@ var Input = class {
8019
8353
  const atCursor = cursorGrapheme?.segment ?? " ";
8020
8354
  const afterCursor = visibleText.slice(cursorDisplay + atCursor.length);
8021
8355
  const marker = this.focused ? CURSOR_MARKER : "";
8022
- const cursorChar = `\x1b[7m${atCursor}\x1b[27m`;
8356
+ const cursorChar = renderFakeCursor(atCursor);
8023
8357
  const textWithCursor = beforeCursor + marker + cursorChar + afterCursor;
8024
8358
  const visualLength = visibleWidth(textWithCursor);
8025
8359
  const padding = " ".repeat(Math.max(0, availableWidth - visualLength));
@@ -9294,7 +9628,13 @@ function renderLatex(source, options = {}) {
9294
9628
  return lines.map((line) => line.slice(indentation).trimEnd()).join("\n").trimEnd().replaceAll(PROTECTED_SPACE, " ");
9295
9629
  }
9296
9630
  const STRICT_STRIKETHROUGH_REGEX = /^(~~)(?=[^\s~])((?:\\.|[^\\])*?(?:\\.|[^\s~\\]))\1(?=[^~]|$)/;
9297
- var StrictStrikethroughTokenizer = class extends Tokenizer {
9631
+ var MarkdownTokenizer = class extends Tokenizer {
9632
+ url(src) {
9633
+ const token = super.url(src);
9634
+ if (!token) return void 0;
9635
+ const punctuationIndex = token.raw.search(cjkPunctuationRegex);
9636
+ return punctuationIndex < 0 ? token : super.url(token.raw.slice(0, punctuationIndex));
9637
+ }
9298
9638
  del(src) {
9299
9639
  const match = STRICT_STRIKETHROUGH_REGEX.exec(src);
9300
9640
  if (!match) return;
@@ -9307,73 +9647,6 @@ var StrictStrikethroughTokenizer = class extends Tokenizer {
9307
9647
  };
9308
9648
  }
9309
9649
  };
9310
- const FULLWIDTH_LEFT_PAREN = 65288;
9311
- const FULLWIDTH_RIGHT_PAREN = 65289;
9312
- const CJK_URL_TERMINATOR_REGEX = /[\u3000-\u303f\uff01-\uff07\uff0a-\uff0f\uff1a-\uff20\uff3b-\uff40\uff5b-\uff65\u2013\u2014\u2018\u2019\u201c\u201d\u2026]/;
9313
- /**
9314
- * Index at which to cut an autolink match, or -1 to keep it whole. Non-paren
9315
- * CJK punctuation terminates the URL outside of full-width parens; full-width
9316
- * parens only terminate it when unbalanced. Punctuation inside a balanced
9317
- * parenthetical (e.g. the ,in (北京,1949年)) stays part of the URL —
9318
- * prose parentheticals contain spaces and never survive marked's match this
9319
- * far, so a balanced group is almost always deliberate URL content.
9320
- */
9321
- function findCjkUrlBoundary(match) {
9322
- let parenDepth = 0;
9323
- let unmatchedOpen = -1;
9324
- for (let i = 0; i < match.length; i++) {
9325
- const code = match.charCodeAt(i);
9326
- if (code === FULLWIDTH_LEFT_PAREN) {
9327
- parenDepth++;
9328
- if (unmatchedOpen === -1) unmatchedOpen = i;
9329
- } else if (code === FULLWIDTH_RIGHT_PAREN) {
9330
- if (parenDepth === 0) return i;
9331
- parenDepth--;
9332
- if (parenDepth === 0) unmatchedOpen = -1;
9333
- } else if (parenDepth === 0 && CJK_URL_TERMINATOR_REGEX.test(match[i])) return i;
9334
- }
9335
- return parenDepth > 0 ? unmatchedOpen : -1;
9336
- }
9337
- var CjkBoundaryUrlTokenizer = class extends StrictStrikethroughTokenizer {
9338
- url(src) {
9339
- const cap = this.rules.inline.url.exec(src);
9340
- if (!cap) return;
9341
- if (cap[2] === "@") {
9342
- const text = cap[0];
9343
- return {
9344
- type: "link",
9345
- raw: text,
9346
- text,
9347
- href: `mailto:${text}`,
9348
- tokens: [{
9349
- type: "text",
9350
- raw: text,
9351
- text
9352
- }]
9353
- };
9354
- }
9355
- const boundary = findCjkUrlBoundary(cap[0]);
9356
- if (boundary !== -1) cap[0] = cap[0].slice(0, boundary);
9357
- if (!cap[0]) return;
9358
- let previous;
9359
- do {
9360
- previous = cap[0];
9361
- cap[0] = this.rules.inline._backpedal.exec(cap[0])?.[0] ?? "";
9362
- } while (previous !== cap[0]);
9363
- const text = cap[0];
9364
- return {
9365
- type: "link",
9366
- raw: text,
9367
- text,
9368
- href: cap[1] === "www." ? `http://${text}` : text,
9369
- tokens: [{
9370
- type: "text",
9371
- raw: text,
9372
- text
9373
- }]
9374
- };
9375
- }
9376
- };
9377
9650
  function isEscaped(source, index) {
9378
9651
  let backslashes = 0;
9379
9652
  for (let position = index - 1; position >= 0 && source[position] === "\\"; position--) backslashes++;
@@ -9423,28 +9696,37 @@ function tokenizeInlineLatex(source) {
9423
9696
  text
9424
9697
  };
9425
9698
  }
9699
+ const TABLE_DELIMITER_ROW_REGEX = /^ {0,3}\|?[ \t]*:?-+:?[ \t]*(?:\|[ \t]*:?-+:?[ \t]*)*\|?[ \t]*$/;
9700
+ function containsTableStart(source) {
9701
+ const lines = source.split("\n");
9702
+ for (let index = 0; index < lines.length - 1; index++) {
9703
+ const delimiterRow = lines[index + 1];
9704
+ if ((delimiterRow.includes("|") || lines[index].includes("|")) && TABLE_DELIMITER_ROW_REGEX.test(delimiterRow)) return true;
9705
+ }
9706
+ return false;
9707
+ }
9426
9708
  function tokenizeBlockLatex(source) {
9427
9709
  const dollarMatch = /^ {0,3}\$\$[ \t]*(?:\n)?([\s\S]*?)\$\$[ \t]*(?:\n|$)/.exec(source);
9428
- if (dollarMatch?.[1]) return {
9710
+ if (dollarMatch?.[1] && !containsTableStart(dollarMatch[1])) return {
9429
9711
  type: "latexBlock",
9430
9712
  raw: dollarMatch[0],
9431
9713
  text: dollarMatch[1].trim()
9432
9714
  };
9433
9715
  const bracketMatch = /^ {0,3}\\\[[ \t]*(?:\n)?([\s\S]*?)\\\][ \t]*(?:\n|$)/.exec(source);
9434
- if (bracketMatch?.[1]) return {
9716
+ if (bracketMatch?.[1] && !containsTableStart(bracketMatch[1])) return {
9435
9717
  type: "latexBlock",
9436
9718
  raw: bracketMatch[0],
9437
9719
  text: bracketMatch[1].trim()
9438
9720
  };
9439
9721
  const pendingBracket = /^ {0,3}\\\[[ \t]*(?:\n)?([\s\S]*)$/.exec(source);
9440
- if (pendingBracket) return {
9722
+ if (pendingBracket?.[1] && !containsTableStart(pendingBracket[1])) return {
9441
9723
  type: "latexBlock",
9442
9724
  raw: pendingBracket[0],
9443
9725
  text: pendingBracket[1],
9444
9726
  pending: true
9445
9727
  };
9446
9728
  const pendingDollar = /^ {0,3}\$\$[ \t]*(?:\n)?([\s\S]*)$/.exec(source);
9447
- if (pendingDollar?.[1] && looksLikePendingDollarMath(pendingDollar[1])) return {
9729
+ if (pendingDollar?.[1] && looksLikePendingDollarMath(pendingDollar[1]) && !containsTableStart(pendingDollar[1])) return {
9448
9730
  type: "latexBlock",
9449
9731
  raw: pendingDollar[0],
9450
9732
  text: pendingDollar[1],
@@ -9489,8 +9771,11 @@ function trimPartialClosingFences(tokens) {
9489
9771
  token.text = token.text.slice(0, -lastLine.length).replace(/\n$/, "");
9490
9772
  }
9491
9773
  const markdownParser = new Marked();
9492
- markdownParser.setOptions({ tokenizer: new CjkBoundaryUrlTokenizer() });
9493
- markdownParser.use({ extensions: [...LATEX_MARKDOWN_EXTENSIONS] });
9774
+ markdownParser.setOptions({ tokenizer: new MarkdownTokenizer() });
9775
+ markdownParser.use({
9776
+ tokenizer: { emStrong: markedCjkFriendly().tokenizer?.emStrong },
9777
+ extensions: [...LATEX_MARKDOWN_EXTENSIONS]
9778
+ });
9494
9779
  var Markdown = class {
9495
9780
  text;
9496
9781
  paddingX;
@@ -9503,6 +9788,8 @@ var Markdown = class {
9503
9788
  cachedWidth;
9504
9789
  cachedLines;
9505
9790
  cachedTokens;
9791
+ blocks;
9792
+ blockHighlightedCode;
9506
9793
  constructor(text, paddingX, paddingY, theme, defaultTextStyle, options) {
9507
9794
  this.text = text;
9508
9795
  this.paddingX = paddingX;
@@ -9513,9 +9800,14 @@ var Markdown = class {
9513
9800
  }
9514
9801
  setText(text) {
9515
9802
  this.text = text;
9516
- this.invalidate();
9803
+ this.clearRenderCache();
9517
9804
  }
9518
9805
  invalidate() {
9806
+ this.clearRenderCache();
9807
+ this.blocks = void 0;
9808
+ this.defaultStylePrefix = void 0;
9809
+ }
9810
+ clearRenderCache() {
9519
9811
  this.cachedText = void 0;
9520
9812
  this.cachedWidth = void 0;
9521
9813
  this.cachedLines = void 0;
@@ -9525,6 +9817,7 @@ var Markdown = class {
9525
9817
  const contentWidth = Math.max(1, width - this.paddingX * 2);
9526
9818
  const text = this.options.transform?.(this.text, contentWidth) ?? this.text;
9527
9819
  if (!text || text.trim() === "") {
9820
+ this.blocks = void 0;
9528
9821
  const result = [];
9529
9822
  this.cachedText = this.text;
9530
9823
  this.cachedWidth = width;
@@ -9542,46 +9835,65 @@ var Markdown = class {
9542
9835
  tokens
9543
9836
  });
9544
9837
  }
9545
- const renderedLines = [];
9838
+ const reuseBlocks = Object.keys(tokens.links).length === 0;
9839
+ const previousBlocks = this.blocks?.deref();
9840
+ const blocks = /* @__PURE__ */ new Map();
9841
+ this.blocks = new WeakRef(blocks);
9842
+ const contentLines = [];
9546
9843
  for (let i = 0; i < tokens.length; i++) {
9547
9844
  const token = tokens[i];
9548
- const nextToken = tokens[i + 1];
9549
- const tokenLines = this.renderToken(token, contentWidth, nextToken?.type);
9550
- for (const tokenLine of tokenLines) renderedLines.push(tokenLine);
9845
+ const nextTokenType = tokens[i + 1]?.type;
9846
+ const block = (reuseBlocks ? blocks.get(token.raw) ?? previousBlocks?.get(token.raw) : void 0) ?? {
9847
+ width: -1,
9848
+ nextTokenType,
9849
+ lines: [],
9850
+ highlightedCode: /* @__PURE__ */ new Map()
9851
+ };
9852
+ if (block.width !== width || block.nextTokenType !== nextTokenType) this.renderBlock(block, token, nextTokenType, width, contentWidth);
9853
+ if (reuseBlocks) blocks.set(token.raw, block);
9854
+ for (const line of block.lines) contentLines.push(line);
9551
9855
  }
9552
- const wrappedLines = [];
9553
- for (const line of renderedLines) if (isImageLine(line)) wrappedLines.push(line);
9554
- else for (const wrappedLine of wrapTextWithAnsi(line, contentWidth)) wrappedLines.push(wrappedLine);
9555
- const leftMargin = " ".repeat(this.paddingX);
9556
- const rightMargin = " ".repeat(this.paddingX);
9557
9856
  const bgFn = this.defaultTextStyle?.bgColor;
9558
- const contentLines = [];
9559
- for (const line of wrappedLines) {
9560
- if (isImageLine(line)) {
9561
- contentLines.push(line);
9562
- continue;
9563
- }
9564
- const lineWithMargins = leftMargin + line + rightMargin;
9565
- if (bgFn) contentLines.push(applyBackgroundToLine(lineWithMargins, width, bgFn));
9566
- else {
9567
- const visibleLen = visibleWidth(lineWithMargins);
9568
- const paddingNeeded = Math.max(0, width - visibleLen);
9569
- contentLines.push(lineWithMargins + " ".repeat(paddingNeeded));
9570
- }
9571
- }
9572
9857
  const emptyLine = " ".repeat(width);
9573
9858
  const emptyLines = [];
9574
9859
  for (let i = 0; i < this.paddingY; i++) {
9575
9860
  const line = bgFn ? applyBackgroundToLine(emptyLine, width, bgFn) : emptyLine;
9576
9861
  emptyLines.push(line);
9577
9862
  }
9863
+ flattenLines(emptyLines);
9578
9864
  const result = emptyLines.concat(contentLines, emptyLines);
9579
- flattenLines(result);
9580
9865
  this.cachedText = this.text;
9581
9866
  this.cachedWidth = width;
9582
9867
  this.cachedLines = result;
9583
9868
  return result.length > 0 ? result : [""];
9584
9869
  }
9870
+ /** Render one top-level block to output lines: wrapped, with margins, and padded or backgrounded to the width. */
9871
+ renderBlock(block, token, nextTokenType, width, contentWidth) {
9872
+ this.blockHighlightedCode = block.highlightedCode;
9873
+ const leftMargin = " ".repeat(this.paddingX);
9874
+ const rightMargin = " ".repeat(this.paddingX);
9875
+ const bgFn = this.defaultTextStyle?.bgColor;
9876
+ const lines = [];
9877
+ for (const line of this.renderToken(token, contentWidth, nextTokenType)) {
9878
+ if (isImageLine(line)) {
9879
+ lines.push(line);
9880
+ continue;
9881
+ }
9882
+ for (const wrappedLine of wrapTextWithAnsi(line, contentWidth)) {
9883
+ const lineWithMargins = leftMargin + wrappedLine + rightMargin;
9884
+ if (bgFn) lines.push(applyBackgroundToLine(lineWithMargins, width, bgFn));
9885
+ else {
9886
+ const paddingNeeded = Math.max(0, width - visibleWidth(lineWithMargins));
9887
+ lines.push(lineWithMargins + " ".repeat(paddingNeeded));
9888
+ }
9889
+ }
9890
+ }
9891
+ this.blockHighlightedCode = void 0;
9892
+ flattenLines(lines);
9893
+ block.lines = lines;
9894
+ block.width = width;
9895
+ block.nextTokenType = nextTokenType;
9896
+ }
9585
9897
  /**
9586
9898
  * Apply default text style to a string.
9587
9899
  * This is the base styling applied to all text content.
@@ -9654,7 +9966,8 @@ var Markdown = class {
9654
9966
  break;
9655
9967
  case "latexBlock": {
9656
9968
  const latexToken = token;
9657
- const rendered = !latexToken.pending && this.options.renderLatex !== false ? renderLatex(latexToken.text, { display: true }) ?? latexToken.raw.trim() : latexToken.raw.trim();
9969
+ let rendered = !latexToken.pending && this.options.renderLatex !== false ? renderLatex(latexToken.text, { display: true }) : void 0;
9970
+ if (rendered === void 0 || rendered.split("\n").some((line) => visibleWidth(line) > width)) rendered = latexToken.raw.trim();
9658
9971
  for (const line of rendered.split("\n")) lines.push(this.applyDefaultStyle(line));
9659
9972
  if (nextTokenType && nextTokenType !== "space") lines.push("");
9660
9973
  break;
@@ -9663,8 +9976,13 @@ var Markdown = class {
9663
9976
  const indent = this.theme.codeBlockIndent ?? " ";
9664
9977
  lines.push(this.theme.codeBlockBorder(`\`\`\`${token.lang || ""}`));
9665
9978
  if (this.theme.highlightCode) {
9666
- const highlightedLines = this.theme.highlightCode(token.text, token.lang);
9667
- for (const hlLine of highlightedLines) lines.push(`${indent}${hlLine}`);
9979
+ const key = `${token.lang ?? ""}\0${token.text}`;
9980
+ let highlighted = this.blockHighlightedCode?.get(key);
9981
+ if (!highlighted) {
9982
+ highlighted = this.theme.highlightCode(token.text, token.lang);
9983
+ this.blockHighlightedCode?.set(key, highlighted);
9984
+ }
9985
+ for (const hlLine of highlighted) lines.push(`${indent}${hlLine}`);
9668
9986
  } else {
9669
9987
  const codeLines = token.text.split("\n");
9670
9988
  for (const codeLine of codeLines) lines.push(`${indent}${this.theme.codeBlock(codeLine)}`);
@@ -9691,7 +10009,12 @@ var Markdown = class {
9691
10009
  const lineWithReappliedStyle = line.replace(/\x1b\[0m/g, `\x1b[0m${quoteStylePrefix}`);
9692
10010
  return quoteStyle(lineWithReappliedStyle);
9693
10011
  };
9694
- const quoteContentWidth = Math.max(1, width - 2);
10012
+ if (width < 3) {
10013
+ const quoteTokens = token.tokens || [];
10014
+ for (let i = 0; i < quoteTokens.length; i++) for (const line of this.renderToken(quoteTokens[i], width, quoteTokens[i + 1]?.type, styleContext)) lines.push(line);
10015
+ break;
10016
+ }
10017
+ const quoteContentWidth = width - 2;
9695
10018
  const quoteInlineStyleContext = {
9696
10019
  applyText: (text) => text,
9697
10020
  stylePrefix: quoteStylePrefix
@@ -9701,7 +10024,7 @@ var Markdown = class {
9701
10024
  for (let i = 0; i < quoteTokens.length; i++) {
9702
10025
  const quoteToken = quoteTokens[i];
9703
10026
  const nextQuoteToken = quoteTokens[i + 1];
9704
- renderedQuoteLines.push(...this.renderToken(quoteToken, quoteContentWidth, nextQuoteToken?.type, quoteInlineStyleContext));
10027
+ for (const line of this.renderToken(quoteToken, quoteContentWidth, nextQuoteToken?.type, quoteInlineStyleContext)) renderedQuoteLines.push(line);
9705
10028
  }
9706
10029
  while (renderedQuoteLines.length > 0 && renderedQuoteLines[renderedQuoteLines.length - 1] === "") renderedQuoteLines.pop();
9707
10030
  for (const quoteLine of renderedQuoteLines) {
@@ -10239,6 +10562,7 @@ function fitValueParts(parts, maxWidth) {
10239
10562
  return parts.slice(0, kept).map((part) => part.text).join("");
10240
10563
  }
10241
10564
  var SettingsList = class {
10565
+ capturesViewportInput = true;
10242
10566
  items;
10243
10567
  filteredItems;
10244
10568
  theme;
@@ -10542,12 +10866,16 @@ var SettingsList = class {
10542
10866
  }
10543
10867
  const kb = getKeybindings();
10544
10868
  const displayItems = this.getDisplayItems();
10869
+ const pageIndex = getSelectPageIndex(kb, data, this.selectedIndex, displayItems.length, this.maxVisible);
10545
10870
  if (kb.matches(data, "tui.select.up")) {
10546
10871
  if (displayItems.length === 0) return;
10547
10872
  this.selectedIndex = this.selectedIndex === 0 ? displayItems.length - 1 : this.selectedIndex - 1;
10548
10873
  } else if (kb.matches(data, "tui.select.down")) {
10549
10874
  if (displayItems.length === 0) return;
10550
10875
  this.selectedIndex = this.selectedIndex === displayItems.length - 1 ? 0 : this.selectedIndex + 1;
10876
+ } else if (pageIndex !== void 0) {
10877
+ if (displayItems.length === 0) return;
10878
+ this.selectedIndex = pageIndex;
10551
10879
  } else if (kb.matches(data, "tui.select.confirm") || data === " " && (!this.searchEnabled || this.searchInput?.getValue().length === 0)) this.activateItem();
10552
10880
  else if (kb.matches(data, "tui.select.cancel")) this.onCancel();
10553
10881
  else if (this.searchEnabled && this.searchInput) {
@@ -10688,6 +11016,12 @@ function getNativePlatformHelper() {
10688
11016
  if (process.platform !== "darwin" && process.platform !== "win32") return void 0;
10689
11017
  return loadNativePlatformHelper(process.platform);
10690
11018
  }
11019
+ /**
11020
+ * Program Status Protocol (OSC 7501): a program tells the terminal whether it is idle, working,
11021
+ * blocked on the user, done, or failed. Only the root record is supported.
11022
+ *
11023
+ * Spec: https://www.superlogical.com/rex/docs/build/program-status
11024
+ */
10691
11025
  /** Feature detection query. A supporting terminal replies with the same body. */
10692
11026
  const PROGRAM_STATUS_QUERY = "\x1B]7501;?\x1B\\";
10693
11027
  /** The reply to {@link PROGRAM_STATUS_QUERY}. Later spec revisions may add pairs after the `?`. */
@@ -10695,7 +11029,6 @@ function isProgramStatusReply(sequence) {
10695
11029
  return /^\x1b\]7501;\?[^\x07\x1b]*(?:\x07|\x1b\\)$/.test(sequence);
10696
11030
  }
10697
11031
  const APP_PATTERN = /^[A-Za-z0-9_.+-]{1,32}$/;
10698
- const CONTROL_CHARACTERS = /[\u0000-\u001f\u007f-\u009f]+/g;
10699
11032
  /** Decoded `msg` limit. Its base64 encoding stays under the 2732-byte encoded limit. */
10700
11033
  const MAX_MESSAGE_BYTES = 2048;
10701
11034
  function truncateUtf8(text, maxBytes) {
@@ -10715,7 +11048,7 @@ function formatProgramStatus(status) {
10715
11048
  const pairs = [`state=${status.state}`];
10716
11049
  if (status.app !== void 0 && APP_PATTERN.test(status.app)) pairs.push(`app=${status.app}`);
10717
11050
  if (status.state === "blocked" && status.kind) pairs.push(`kind=${status.kind}`);
10718
- const message = truncateUtf8((status.message ?? "").replace(CONTROL_CHARACTERS, " ").trim(), MAX_MESSAGE_BYTES);
11051
+ const message = truncateUtf8(replaceControlCharacters(status.message ?? "").trim(), MAX_MESSAGE_BYTES);
10719
11052
  if (message) pairs.push(`msg=${Buffer.from(message, "utf8").toString("base64")}`);
10720
11053
  return `\x1b]7501;${pairs.join(":")}\x1b\\`;
10721
11054
  }
@@ -10742,6 +11075,10 @@ const DEFAULT_SEQUENCE_TIMEOUT_MS = 50;
10742
11075
  const DEFAULT_ESCAPE_TIMEOUT_MS$1 = 10;
10743
11076
  const BRACKETED_PASTE_START$1 = "\x1B[200~";
10744
11077
  const BRACKETED_PASTE_END$1 = "\x1B[201~";
11078
+ const TERMINAL_REPLY_HEADER_PATTERN = /^\x1b(?:\](?:1[01];|4;\d{1,3};|7501;\?)|P>\||_G(?:[a-z]=\d+,)*[a-z]=\d+;)/;
11079
+ function isControlString(data) {
11080
+ return data.startsWith(`${ESC}]`) || data.startsWith(`${ESC}P`) || data.startsWith(`${ESC}_`);
11081
+ }
10745
11082
  /**
10746
11083
  * A never-terminating ESC prefix (corrupt stream, oversized paste) must not
10747
11084
  * reslice the buffer once per byte — cap the scan and degrade the ESC to a
@@ -10833,8 +11170,20 @@ function extractCompleteSequences(buffer) {
10833
11170
  while (pos < buffer.length) {
10834
11171
  const remaining = buffer.slice(pos);
10835
11172
  if (remaining.startsWith(ESC)) {
11173
+ const terminalReply = isControlString(remaining) && TERMINAL_REPLY_HEADER_PATTERN.test(remaining);
10836
11174
  let seqEnd = 1;
10837
11175
  while (seqEnd <= remaining.length) {
11176
+ if (terminalReply && seqEnd > 2) {
11177
+ const char = remaining[seqEnd - 1];
11178
+ if (char === "" || char === "") {
11179
+ pos += seqEnd;
11180
+ break;
11181
+ }
11182
+ if (char === ESC && seqEnd < remaining.length && remaining[seqEnd] !== "\\") {
11183
+ pos += seqEnd - 1;
11184
+ break;
11185
+ }
11186
+ }
10838
11187
  const candidate = remaining.slice(0, seqEnd);
10839
11188
  const status = isCompleteSequence(candidate);
10840
11189
  if (status === "complete") {
@@ -10952,10 +11301,14 @@ var StdinBuffer = class extends EventEmitter {
10952
11301
  this.buffer = result.remainder;
10953
11302
  for (const sequence of result.sequences) this.emitDataSequence(sequence);
10954
11303
  if (this.buffer.length > 0) {
11304
+ if (TERMINAL_REPLY_HEADER_PATTERN.test(this.buffer)) return;
10955
11305
  const timeoutMs = this.buffer === ESC ? this.escapeTimeoutMs : this.timeoutMs;
10956
11306
  this.timeout = setTimeout(() => {
10957
11307
  const flushed = this.flush();
10958
- for (const sequence of flushed) this.emitDataSequence(sequence);
11308
+ for (const sequence of flushed) if (sequence.length > 2 && isControlString(sequence)) {
11309
+ this.emitDataSequence(sequence.slice(0, 2));
11310
+ this.process(sequence.slice(2));
11311
+ } else this.emitDataSequence(sequence);
10959
11312
  }, timeoutMs);
10960
11313
  }
10961
11314
  }
@@ -11029,6 +11382,18 @@ function parseKeyboardProtocolNegotiationSequence(sequence) {
11029
11382
  function isKeyboardProtocolNegotiationSequencePrefix(sequence) {
11030
11383
  return sequence === "\x1B[" || /^\x1b\[\?[\d;]*$/.test(sequence);
11031
11384
  }
11385
+ /**
11386
+ * Whether a complete PRIMARY device-attributes reply (`CSI ? ... c`) declares
11387
+ * the SIXEL attribute (`4`), or `undefined` when this is not a primary DA1.
11388
+ *
11389
+ * Parameters are compared as whole tokens: a substring test would wrongly
11390
+ * accept `14`, `42` or `24` as evidence of SIXEL support (X071).
11391
+ */
11392
+ function primaryDeviceAttributesDeclareSixel(sequence) {
11393
+ const match = /^\x1b\[\?([\d;]*)c$/.exec(sequence);
11394
+ if (!match) return void 0;
11395
+ return match[1].split(";").some((token) => token !== "" && Number.parseInt(token, 10) === 4);
11396
+ }
11032
11397
  function isAppleTerminalSession() {
11033
11398
  return process.platform === "darwin" && process.env.TERM_PROGRAM === "Apple_Terminal";
11034
11399
  }
@@ -11043,8 +11408,11 @@ function refreshTerminalDimensions() {
11043
11408
  process.kill(process.pid, "SIGWINCH");
11044
11409
  } catch {}
11045
11410
  }
11411
+ function isNativeShiftEnterCandidate(data) {
11412
+ return data === "\r" || data === "\x1B\r";
11413
+ }
11046
11414
  function normalizeNativeShiftEnterInput(data, shouldDetectNativeShiftEnter, isShiftPressed) {
11047
- if (shouldDetectNativeShiftEnter && data === "\r" && isShiftPressed) return NATIVE_SHIFT_ENTER_SEQUENCE;
11415
+ if (shouldDetectNativeShiftEnter && isNativeShiftEnterCandidate(data) && isShiftPressed) return NATIVE_SHIFT_ENTER_SEQUENCE;
11048
11416
  return data;
11049
11417
  }
11050
11418
  const DEFAULT_ESCAPE_TIMEOUT_MS = 10;
@@ -11091,6 +11459,14 @@ var ProcessTerminal = class {
11091
11459
  pendingKeyboardProtocolDeviceAttributes = 0;
11092
11460
  keyboardProtocolNegotiationBuffer = "";
11093
11461
  keyboardProtocolBufferFlushTimer;
11462
+ /** Passive DA1 SIXEL observers (X071). One store; no reply replay buffer. */
11463
+ sixelObservers = /* @__PURE__ */ new Set();
11464
+ /**
11465
+ * Last observed primary-DA1 SIXEL answer for the PHYSICAL terminal this
11466
+ * instance represents (X071). Survives `stop()` and `start()`: the same
11467
+ * hardware cannot un-learn the capability between a Main and an Alt screen.
11468
+ */
11469
+ lastObservedSixel = void 0;
11094
11470
  stdinBuffer;
11095
11471
  stdinDataHandler;
11096
11472
  progressInterval;
@@ -11175,6 +11551,7 @@ var ProcessTerminal = class {
11175
11551
  this.scheduleKeyboardProtocolNegotiationBufferFlush();
11176
11552
  return;
11177
11553
  }
11554
+ if (negotiation?.parsed.type === "device-attributes") this.observeSixelDeviceAttributes(negotiation.sequence);
11178
11555
  if (negotiation && this.handleKeyboardProtocolNegotiationSequence(negotiation.parsed)) return;
11179
11556
  this.forwardInputSequence(negotiation?.sequence ?? sequence);
11180
11557
  });
@@ -11215,6 +11592,33 @@ var ProcessTerminal = class {
11215
11592
  process.stdout.write(`${KITTY_KEYBOARD_PROTOCOL_QUERY}${programStatusQuery}${DEVICE_ATTRIBUTES_QUERY}`);
11216
11593
  this.writeProgramStatus();
11217
11594
  }
11595
+ /**
11596
+ * Passive DA1 observation; see `Terminal.onSixelSupport` (X071). The
11597
+ * registration is committed BEFORE any synchronous delivery so a listener
11598
+ * that unsubscribes itself (or disposes its owner) inside the callback
11599
+ * observes the already-committed state.
11600
+ */
11601
+ onSixelSupport(listener) {
11602
+ this.sixelObservers.add(listener);
11603
+ const known = this.lastObservedSixel;
11604
+ if (known !== void 0) listener(known);
11605
+ return () => {
11606
+ this.sixelObservers.delete(listener);
11607
+ };
11608
+ }
11609
+ /**
11610
+ * Record the SIXEL attribute of one COMPLETE primary DA1 reply (X071).
11611
+ *
11612
+ * Called before the keyboard-negotiation sentinel may consume the same
11613
+ * reply. A repeated identical answer does not notify again.
11614
+ */
11615
+ observeSixelDeviceAttributes(sequence) {
11616
+ const supported = primaryDeviceAttributesDeclareSixel(sequence);
11617
+ if (supported === void 0) return;
11618
+ if (this.lastObservedSixel === supported) return;
11619
+ this.lastObservedSixel = supported;
11620
+ for (const listener of [...this.sixelObservers]) listener(supported);
11621
+ }
11218
11622
  handleKeyboardProtocolNegotiationSequence(negotiationSequence) {
11219
11623
  this.clearKeyboardProtocolNegotiationBuffer();
11220
11624
  if (negotiationSequence.type === "device-attributes") {
@@ -11291,7 +11695,7 @@ var ProcessTerminal = class {
11291
11695
  }
11292
11696
  forwardInputSequence(sequence) {
11293
11697
  if (!this.inputHandler) return;
11294
- const shouldDetectNativeShiftEnter = sequence === "\r" && (isAppleTerminalSession() || process.platform === "win32");
11698
+ const shouldDetectNativeShiftEnter = isNativeShiftEnterCandidate(sequence) && (isAppleTerminalSession() || process.platform === "win32");
11295
11699
  const input = normalizeNativeShiftEnterInput(sequence, shouldDetectNativeShiftEnter, shouldDetectNativeShiftEnter && isNativeModifierPressed("shift"));
11296
11700
  this.inputHandler(input);
11297
11701
  }
@@ -11384,6 +11788,18 @@ var ProcessTerminal = class {
11384
11788
  if (process.stdin.setRawMode) process.stdin.setRawMode(this.wasRaw);
11385
11789
  this.started = false;
11386
11790
  }
11791
+ restoreOnExit(before, after) {
11792
+ let sequence = before;
11793
+ if (this.progressState !== "clear") sequence += TERMINAL_PROGRESS_CLEAR_SEQUENCE;
11794
+ if (this.programStatusSupported && this.programStatus) sequence += formatProgramStatus({ state: "clear" });
11795
+ sequence += "\x1B[?2004l";
11796
+ if (this.keyboardProtocolPushed || this._kittyProtocolActive) sequence += "\x1B[<u";
11797
+ if (this._modifyOtherKeysActive) sequence += "\x1B[>4;0m";
11798
+ sequence += after;
11799
+ try {
11800
+ fs.writeSync(process.stdout.fd, sequence);
11801
+ } catch {}
11802
+ }
11387
11803
  write(data) {
11388
11804
  process.stdout.write(data);
11389
11805
  if (this.writeLogPath) try {
@@ -11416,7 +11832,7 @@ var ProcessTerminal = class {
11416
11832
  process.stdout.write("\x1B[2J\x1B[H");
11417
11833
  }
11418
11834
  setTitle(title) {
11419
- process.stdout.write(`\x1b]0;${title}\x07`);
11835
+ process.stdout.write(`\x1b]0;${replaceControlCharacters(title)}\x07`);
11420
11836
  }
11421
11837
  setProgramStatus(status) {
11422
11838
  this.programStatus = status.state === "clear" ? void 0 : status;
@@ -11738,7 +12154,9 @@ var AltScreenFlashContainer = class {
11738
12154
  });
11739
12155
  }
11740
12156
  };
11741
- const OSC133_ZONE_PREFIX$1 = /^(?:\x1b\]133;[ABC](?:\x07|\x1b\\))+/;
12157
+ const OSC133_ZONE_PREFIX$2 = /^(?:\x1b\]133;[ABC](?:\x07|\x1b\\))+/;
12158
+ /** The largest number of image body rows an upward crop search may cross (X074). */
12159
+ const MAX_SIXEL_CROP_SCAN_ROWS = 12;
11742
12160
  function intersect(a, b) {
11743
12161
  const x = Math.max(a.x, b.x);
11744
12162
  const y = Math.max(a.y, b.y);
@@ -11969,14 +12387,17 @@ function getScrollbarGeometry(box, includeHiddenAuto = false) {
11969
12387
  maxScrollTop
11970
12388
  };
11971
12389
  }
11972
- function paintScrollbar(box, screen, totalWidth) {
12390
+ function paintScrollbar(box, screen, totalWidth, sixelScreen) {
11973
12391
  const geometry = getScrollbarGeometry(box);
11974
12392
  if (!geometry || !box.scrollView) return;
11975
12393
  for (let offset = 0; offset < geometry.trackHeight; offset++) {
11976
12394
  const row = geometry.trackTop + offset;
11977
12395
  if (row < box.clip.y || row >= box.clip.y + box.clip.height || row < 0 || row >= screen.length) continue;
11978
12396
  const replacement = row >= geometry.thumbTop && row < geometry.thumbTop + geometry.thumbHeight ? box.scrollView.scrollbarThumbStyle(box.scrollView.isScrollbarActive ? "█" : "┃") : box.scrollView.scrollbarTrackStyle("│");
11979
- screen[row] = replaceScrollbarCell(screen[row] ?? "", geometry.column, totalWidth, replacement, box.scrollView.scrollbar !== "always");
12397
+ const line = screen[row] ?? "";
12398
+ const footprint = sixelScreen?.footprint(line);
12399
+ if (footprint !== void 0 && footprint.columns <= geometry.column) continue;
12400
+ screen[row] = replaceScrollbarCell(footprint === void 0 ? line : "", geometry.column, totalWidth, replacement, box.scrollView.scrollbar !== "always");
11980
12401
  }
11981
12402
  }
11982
12403
  /** The managed virtual image row bound; only this window may be scanned. */
@@ -12017,7 +12438,22 @@ function findRelocatedVirtualAnchor(box, firstRow, lastRow) {
12017
12438
  };
12018
12439
  }
12019
12440
  }
12020
- function paintBox(box, screen, totalWidth) {
12441
+ function sixelBlock(line, port) {
12442
+ if (port === void 0) return void 0;
12443
+ const candidate = port.candidate(line);
12444
+ if (candidate !== void 0) return {
12445
+ kind: "candidate",
12446
+ rows: candidate.layoutRows,
12447
+ fallback: candidate.fallback
12448
+ };
12449
+ const footprint = port.footprint(line);
12450
+ if (footprint !== void 0) return {
12451
+ kind: "dcs",
12452
+ rows: footprint.rows
12453
+ };
12454
+ }
12455
+ function paintBox(box, screen, totalWidth, context) {
12456
+ const sixelScreen = context.sixelScreen;
12021
12457
  if (box.lines) {
12022
12458
  const offset = box.lineOffset ?? 0;
12023
12459
  const firstRow = Math.max(box.rect.y, box.clip.y, 0);
@@ -12027,7 +12463,7 @@ function paintBox(box, screen, totalWidth) {
12027
12463
  const sourceIndex = offset + row - box.rect.y;
12028
12464
  const sourceLine = box.lines[sourceIndex];
12029
12465
  if (sourceLine === void 0) continue;
12030
- let line = sourceLine.replace(OSC133_ZONE_PREFIX$1, "");
12466
+ let line = sourceLine.replace(OSC133_ZONE_PREFIX$2, "");
12031
12467
  if (line.startsWith("\x1B_pi:tmux-image:v1:i=")) {
12032
12468
  const marker = getManagedKittyVirtualMarker(line);
12033
12469
  if (marker === void 0) throw new Error("managed kitty virtual marker is malformed");
@@ -12036,6 +12472,34 @@ function paintBox(box, screen, totalWidth) {
12036
12472
  line = line.slice(marker.sequence.length);
12037
12473
  }
12038
12474
  if (relocated !== void 0 && sourceIndex === relocated.sourceIndex) line = relocated.sequence + line;
12475
+ const block = sixelBlock(line, sixelScreen);
12476
+ if (block !== void 0) {
12477
+ const fullWidthCell = box.rect.x === 0 && box.rect.width >= totalWidth;
12478
+ const clipBottom = Math.min(screen.length, box.clip.y + box.clip.height);
12479
+ const visibleRows = Math.min(block.rows, clipBottom - row);
12480
+ const scrollbar = box.scrollView === void 0 ? void 0 : getScrollbarGeometry(box);
12481
+ const scrollbarClaimsRow = scrollbar !== void 0 && row <= scrollbar.trackTop + scrollbar.trackHeight - 1 && row + visibleRows - 1 >= scrollbar.trackTop;
12482
+ if (block.kind === "candidate") {
12483
+ if (fullWidthCell && visibleRows > 0 && !scrollbarClaimsRow) {
12484
+ context.sixelDemands.push({
12485
+ line,
12486
+ cropTopRows: 0,
12487
+ visibleRows,
12488
+ physicalRow: row
12489
+ });
12490
+ screen[row] = sixelScreen?.materialize(line, 0, visibleRows) ?? block.fallback;
12491
+ } else screen[row] = block.fallback;
12492
+ continue;
12493
+ }
12494
+ if (fullWidthCell && visibleRows > 0) {
12495
+ if (visibleRows >= block.rows) screen[row] = line;
12496
+ else {
12497
+ const cropped = sixelScreen?.crop(line, 0, visibleRows);
12498
+ screen[row] = cropped ?? "";
12499
+ }
12500
+ }
12501
+ continue;
12502
+ }
12039
12503
  const imageMetadata = getKittyImageMetadata(line);
12040
12504
  if (imageMetadata) {
12041
12505
  const clipBottom = Math.min(screen.length, box.clip.y + box.clip.height);
@@ -12046,23 +12510,56 @@ function paintBox(box, screen, totalWidth) {
12046
12510
  else screen[row] = compositeTuiLine(screen[row] ?? "", line, box.rect.x, box.rect.width, totalWidth);
12047
12511
  }
12048
12512
  }
12049
- for (const child of box.children) paintBox(child, screen, totalWidth);
12050
- if (box.scrollView && box.scrollContentLines && box.scrollView.scrollTop > 0 && box.rect.height > 0) for (let imageRow = box.scrollView.scrollTop - 1; imageRow >= 0; imageRow--) {
12051
- const imageLine = box.scrollContentLines[imageRow] ?? "";
12052
- const metadata = getKittyImageMetadata(imageLine);
12053
- if (metadata) {
12054
- const hiddenRows = box.scrollView.scrollTop - imageRow;
12055
- if (hiddenRows < metadata.rows) {
12056
- const cropped = cropKittyImageLine(imageLine, hiddenRows, Math.min(box.rect.height, metadata.rows - hiddenRows));
12057
- if (box.rect.x === 0 && box.rect.width >= totalWidth) screen[box.rect.y] = cropped;
12513
+ for (const child of box.children) paintBox(child, screen, totalWidth, context);
12514
+ if (box.scrollView && box.scrollContentLines && box.scrollView.scrollTop > 0 && box.rect.height > 0) {
12515
+ const scrollTop = box.scrollView.scrollTop;
12516
+ const kittyScanFloor = Math.max(0, scrollTop - getMaxKittyImageRows());
12517
+ const sixelScanFloor = Math.max(0, scrollTop - MAX_SIXEL_CROP_SCAN_ROWS);
12518
+ let sixelSearch = true;
12519
+ let kittySearch = true;
12520
+ for (let imageRow = scrollTop - 1; imageRow >= 0; imageRow--) {
12521
+ if (!sixelSearch && !kittySearch) break;
12522
+ const imageLine = box.scrollContentLines[imageRow] ?? "";
12523
+ if (sixelSearch) {
12524
+ const block = sixelBlock(imageLine, sixelScreen);
12525
+ if (block !== void 0) {
12526
+ const hiddenRows = scrollTop - imageRow;
12527
+ const visibleRows = Math.min(box.rect.height, block.rows - hiddenRows);
12528
+ if (hiddenRows < block.rows && visibleRows > 0 && box.rect.x === 0 && box.rect.width >= totalWidth) {
12529
+ if (block.kind === "candidate") {
12530
+ context.sixelDemands.push({
12531
+ line: imageLine,
12532
+ cropTopRows: hiddenRows,
12533
+ visibleRows,
12534
+ physicalRow: box.rect.y
12535
+ });
12536
+ screen[box.rect.y] = sixelScreen?.materialize(imageLine, hiddenRows, visibleRows) ?? block.fallback;
12537
+ } else {
12538
+ const cropped = sixelScreen?.crop(imageLine, hiddenRows, visibleRows);
12539
+ if (cropped !== void 0) screen[box.rect.y] = cropped;
12540
+ }
12541
+ }
12542
+ break;
12543
+ }
12058
12544
  }
12059
- break;
12545
+ if (kittySearch) {
12546
+ const metadata = getKittyImageMetadata(imageLine);
12547
+ if (metadata) {
12548
+ const hiddenRows = scrollTop - imageRow;
12549
+ if (hiddenRows < metadata.rows) {
12550
+ const cropped = cropKittyImageLine(imageLine, hiddenRows, Math.min(box.rect.height, metadata.rows - hiddenRows));
12551
+ if (box.rect.x === 0 && box.rect.width >= totalWidth) screen[box.rect.y] = cropped;
12552
+ }
12553
+ break;
12554
+ }
12555
+ }
12556
+ if (sixelSearch && (imageLine !== "" || imageRow <= sixelScanFloor)) sixelSearch = false;
12557
+ if (kittySearch && imageRow <= kittyScanFloor) kittySearch = false;
12060
12558
  }
12061
- if (imageLine !== "") break;
12062
12559
  }
12063
- paintScrollbar(box, screen, totalWidth);
12560
+ paintScrollbar(box, screen, totalWidth, sixelScreen);
12064
12561
  }
12065
- function renderLayoutFrame(root, width, height, requestRender) {
12562
+ function renderLayoutFrame(root, width, height, requestRender, sixelScreen) {
12066
12563
  const safeWidth = Math.max(1, Math.floor(width));
12067
12564
  const safeHeight = Math.max(1, Math.floor(height));
12068
12565
  const context = {
@@ -12073,7 +12570,9 @@ function renderLayoutFrame(root, width, height, requestRender) {
12073
12570
  renderCache: /* @__PURE__ */ new Map(),
12074
12571
  maxWidthCache: /* @__PURE__ */ new Map(),
12075
12572
  requestRender,
12076
- primaryScrollView: void 0
12573
+ primaryScrollView: void 0,
12574
+ sixelScreen,
12575
+ sixelDemands: []
12077
12576
  };
12078
12577
  const rootBox = layoutComponent(context, root, 0, 0, safeWidth, safeHeight, {
12079
12578
  x: 0,
@@ -12082,12 +12581,13 @@ function renderLayoutFrame(root, width, height, requestRender) {
12082
12581
  height: safeHeight
12083
12582
  });
12084
12583
  const lines = Array.from({ length: safeHeight }, () => "");
12085
- paintBox(rootBox, lines, safeWidth);
12584
+ paintBox(rootBox, lines, safeWidth, context);
12086
12585
  return {
12087
12586
  root: rootBox,
12088
12587
  width: safeWidth,
12089
12588
  height: safeHeight,
12090
12589
  lines,
12590
+ sixelDemands: context.sixelDemands,
12091
12591
  ...context.primaryScrollView === void 0 ? {} : { primaryScrollView: context.primaryScrollView }
12092
12592
  };
12093
12593
  }
@@ -12206,7 +12706,7 @@ const FOCUS_IN = "\x1B[I";
12206
12706
  const FOCUS_OUT = "\x1B[O";
12207
12707
  const BEGIN_SYNCHRONIZED_OUTPUT = "\x1B[?2026h";
12208
12708
  const END_SYNCHRONIZED_OUTPUT = "\x1B[?2026l";
12209
- const OSC133_ZONE_PREFIX = /^(?:\x1b\]133;[ABC](?:\x07|\x1b\\))+/;
12709
+ const OSC133_ZONE_PREFIX$1 = /^(?:\x1b\]133;[ABC](?:\x07|\x1b\\))+/;
12210
12710
  const OSC133_PROMPT_START = /^\x1b\]133;A(?:\x07|\x1b\\)/;
12211
12711
  const PAGE_SCROLL_OVERLAP = 4;
12212
12712
  const ALT_WHEEL_SCROLL_MULTIPLIER = 5;
@@ -12215,7 +12715,15 @@ const MAX_CACHED_OFFSCREEN_KITTY_TRANSMISSION_BYTES = 33554432;
12215
12715
  const MAX_CACHED_OFFSCREEN_KITTY_DECODED_BYTES = 67108864;
12216
12716
  const DOUBLE_CLICK_INTERVAL_MS = 500;
12217
12717
  const COPY_ERROR_FLASH_DURATION_MS = 5e3;
12218
- const TERMINAL_WORD_SELECTION_JOINERS = /* @__PURE__ */ new Set(["/", "-"]);
12718
+ const TERMINAL_WORD_SELECTION_JOINERS = /* @__PURE__ */ new Set([
12719
+ "/",
12720
+ "-",
12721
+ "+",
12722
+ "\\",
12723
+ "~",
12724
+ "_",
12725
+ "."
12726
+ ]);
12219
12727
  const wordSegmenter = getWordSegmenter();
12220
12728
  /** Alternate-screen TUI with a scrollable, application-owned viewport. */
12221
12729
  var TuiAltScreen = class extends TuiBase {
@@ -12236,6 +12744,14 @@ var TuiAltScreen = class extends TuiBase {
12236
12744
  imageProtocolOverride;
12237
12745
  savedCapabilities;
12238
12746
  uploadedKittyImages = /* @__PURE__ */ new Map();
12747
+ /**
12748
+ * Per-row trusted SIXEL block height of the LAST painted frame (X074).
12749
+ *
12750
+ * Cached instead of re-derived from the line: the previous anchor is a
12751
+ * registered DCS only while its owner lives, and a disposed raster must still
12752
+ * have its whole footprint erased.
12753
+ */
12754
+ previousSixelRows = [];
12239
12755
  selectionAnchor;
12240
12756
  selectionFocus;
12241
12757
  selectionGranularity = "character";
@@ -12294,7 +12810,7 @@ var TuiAltScreen = class extends TuiBase {
12294
12810
  onBeforeViewportInput;
12295
12811
  scrollbarBoundaryNotified;
12296
12812
  constructor(terminal, showHardwareCursor, logDirectory, options = {}) {
12297
- super(terminal, showHardwareCursor, logDirectory);
12813
+ super(terminal, showHardwareCursor, logDirectory, options.sixelScreen);
12298
12814
  this.implicitDocument = {
12299
12815
  render: (width) => super.render(width),
12300
12816
  handleMouse: (event) => super.handleMouse(event),
@@ -12479,8 +12995,8 @@ var TuiAltScreen = class extends TuiBase {
12479
12995
  if (options.preserveScreen) this.terminal.write(`${BEGIN_SYNCHRONIZED_OUTPUT}${EXIT_ALT_SCREEN}\x1b[?25h${END_SYNCHRONIZED_OUTPUT}`);
12480
12996
  else {
12481
12997
  const width = Math.max(1, this.terminal.columns);
12482
- const documentLines = this.render(width).map((line) => line.replace(OSC133_ZONE_PREFIX, ""));
12483
- this.lastDocument = this.applyLineResets(documentLines.map((line) => line.replaceAll(CURSOR_MARKER, ""))).map((line) => isImageLine(line) || visibleWidth(line) <= width ? line : sliceByColumn(line, 0, width, true));
12998
+ const documentLines = this.resolveFakeCursors(this.render(width)).map((line) => line.replace(OSC133_ZONE_PREFIX$1, "")).map((line) => this.sixelScreen?.candidate(line)?.fallback ?? line);
12999
+ this.lastDocument = this.applyLineResets(documentLines.map((line) => line.replaceAll(CURSOR_MARKER, ""))).map((line) => this.sixelFootprint(line) !== void 0 ? "" : isImageLine(line) || visibleWidth(line) <= width ? line : sliceByColumn(line, 0, width, true));
12484
13000
  let buffer = `${BEGIN_SYNCHRONIZED_OUTPUT}${EXIT_ALT_SCREEN}${DISABLE_AUTOWRAP}`;
12485
13001
  for (let row = 0; row < this.lastDocument.length; row++) {
12486
13002
  if (row > 0) buffer += "\r\n";
@@ -12494,6 +13010,14 @@ var TuiAltScreen = class extends TuiBase {
12494
13010
  this.savedCapabilities = void 0;
12495
13011
  }
12496
13012
  }
13013
+ getExitRestorePrefix() {
13014
+ const prefix = super.getExitRestorePrefix();
13015
+ if (!this.altScreenActive) return prefix;
13016
+ return `${END_SYNCHRONIZED_OUTPUT}${this.mouseEnabled ? DISABLE_MOUSE : ""}${ENABLE_AUTOWRAP}${prefix}`;
13017
+ }
13018
+ getExitRestoreSuffix() {
13019
+ return `${super.getExitRestoreSuffix()}${this.altScreenActive ? `${EXIT_ALT_SCREEN}\x1b[?25h` : ""}`;
13020
+ }
12497
13021
  deleteKittyImages() {
12498
13022
  return this.imageProtocol === "kitty" ? deleteAllKittyImages() : "";
12499
13023
  }
@@ -12539,10 +13063,75 @@ var TuiAltScreen = class extends TuiBase {
12539
13063
  }
12540
13064
  resetRenderState() {
12541
13065
  this.previousScreen = [];
13066
+ this.previousSixelRows = [];
12542
13067
  this.previousScreenWidth = 0;
12543
13068
  this.previousScreenHeight = 0;
12544
13069
  this.currentLayout = void 0;
12545
13070
  }
13071
+ /**
13072
+ * Per-row trusted SIXEL block heights for this frame, dropping any block a
13073
+ * visible overlay paints over (X074).
13074
+ *
13075
+ * The raster is ONE command covering its whole footprint and it is written
13076
+ * LAST, so a per-row decision would either cover the overlay text or leave
13077
+ * half a picture. Such a block yields this frame; its identity row above stays
13078
+ * on screen and the block returns when the overlay is gone (the anchor line
13079
+ * changes, so the next frame re-enters the changed range).
13080
+ */
13081
+ /**
13082
+ * Report this frame's physical SIXEL set after the write (X074).
13083
+ *
13084
+ * `sixelDemands` is the final layout's visible set; a block that materialized
13085
+ * is retained with its exact DCS (emitted only when this frame really wrote
13086
+ * that row), while a granted-but-unready block has no DCS and simply keeps
13087
+ * its grant for the owner to task the lane.
13088
+ */
13089
+ commitSixelFrame(frame, screen, changedRows, repainted) {
13090
+ const port = this.sixelScreen;
13091
+ if (port === void 0) return;
13092
+ const retained = [];
13093
+ for (const demand of frame.sixelDemands) {
13094
+ const row = demand.physicalRow;
13095
+ const line = screen[row] ?? "";
13096
+ const footprint = port.footprint(line);
13097
+ if (footprint === void 0) continue;
13098
+ retained.push({
13099
+ row,
13100
+ line: demand.line,
13101
+ dcs: line,
13102
+ cropTopRows: demand.cropTopRows,
13103
+ visibleRows: footprint.rows,
13104
+ emitted: repainted || changedRows[row] !== false
13105
+ });
13106
+ }
13107
+ retained.sort((left, right) => right.row - left.row);
13108
+ port.framePainted(this, retained.map(({ line, dcs, cropTopRows, visibleRows, emitted }) => ({
13109
+ line,
13110
+ dcs,
13111
+ cropTopRows,
13112
+ visibleRows,
13113
+ emitted
13114
+ })));
13115
+ }
13116
+ prepareSixelRows(screen) {
13117
+ const rows = new Array(screen.length).fill(0);
13118
+ let any = false;
13119
+ for (let row = 0; row < screen.length; row++) {
13120
+ const footprint = this.sixelFootprint(screen[row] ?? "");
13121
+ if (footprint === void 0) continue;
13122
+ rows[row] = footprint.rows;
13123
+ any = true;
13124
+ }
13125
+ if (!any) return rows;
13126
+ if (this.hasOverlayEntries) for (let row = 0; row < rows.length; row++) {
13127
+ const height = rows[row] ?? 0;
13128
+ if (height === 0) continue;
13129
+ if (!this.linesCoveredByOverlay(row, row + height - 1, screen.length)) continue;
13130
+ screen[row] = "";
13131
+ rows[row] = 0;
13132
+ }
13133
+ return rows;
13134
+ }
12546
13135
  scrollBy(lines) {
12547
13136
  this.getPrimaryScrollView().scrollBy(lines);
12548
13137
  this.requestRender();
@@ -12649,7 +13238,9 @@ var TuiAltScreen = class extends TuiBase {
12649
13238
  return false;
12650
13239
  }
12651
13240
  const shouldRevealSelection = search.selectionMode !== "retain";
12652
- const result = search.index.search(lines, search.query);
13241
+ const isEmptyImageRow = (line) => this.sixelFootprint(line) !== void 0 || this.sixelScreen?.candidate(line) !== void 0;
13242
+ const corpus = lines.some(isEmptyImageRow) ? lines.map((line) => isEmptyImageRow(line) ? "" : line) : lines;
13243
+ const result = search.index.search(corpus, search.query);
12653
13244
  const matches = result.matches;
12654
13245
  search.matches = matches;
12655
13246
  if (!result.changed && search.selectionMode === "retain") return false;
@@ -12693,6 +13284,7 @@ var TuiAltScreen = class extends TuiBase {
12693
13284
  flash(message, durationMs) {
12694
13285
  this.flashes.flash(message, durationMs);
12695
13286
  }
13287
+ /** Focused overlays and components that capture viewport input receive viewport keys instead of the transcript. */
12696
13288
  shouldDeferViewportInputToOverlay() {
12697
13289
  return this.isOverlayFocused() && this.activeSearch?.overlay?.isFocused() !== true;
12698
13290
  }
@@ -12853,6 +13445,7 @@ var TuiAltScreen = class extends TuiBase {
12853
13445
  }
12854
13446
  }
12855
13447
  if (this.shouldDeferViewportInputToOverlay()) return void 0;
13448
+ if (this.getFocusedComponent()?.capturesViewportInput === true) return void 0;
12856
13449
  if (!isRelease && this.onBeforeViewportInput?.(data) === true) return { consume: true };
12857
13450
  const primaryScrollable = this.getPrimaryScrollView().canScroll;
12858
13451
  if (keybindings.matches(data, "tui.altScreen.search")) {
@@ -13584,6 +14177,10 @@ var TuiAltScreen = class extends TuiBase {
13584
14177
  const lines = [];
13585
14178
  for (let row = selection.start.row; row <= selection.end.row; row++) {
13586
14179
  const line = sourceLines[row] ?? "";
14180
+ if (this.isRenderableImageLine(line)) {
14181
+ lines.push("");
14182
+ continue;
14183
+ }
13587
14184
  const columns = this.getSelectionColumns(line, row, selection);
13588
14185
  const sliced = stripTerminalSequences(sliceByColumn(line, columns.start, Math.max(0, columns.end - columns.start), true)).trimEnd();
13589
14186
  lines.push(columns.start === 0 ? sliced.replace(/^ {1,3}/, "") : sliced);
@@ -13691,7 +14288,7 @@ var TuiAltScreen = class extends TuiBase {
13691
14288
  const result = [...screen];
13692
14289
  for (const [row, ranges] of rangesByRow) {
13693
14290
  let line = result[row] ?? "";
13694
- if (isImageLine(line)) continue;
14291
+ if (this.isRenderableImageLine(line)) continue;
13695
14292
  const lineWidth = visibleWidth(line);
13696
14293
  for (const range of ranges.sort((a, b) => b.startCol - a.startCol)) {
13697
14294
  const startCol = Math.min(range.startCol, lineWidth);
@@ -13759,7 +14356,7 @@ var TuiAltScreen = class extends TuiBase {
13759
14356
  };
13760
14357
  }
13761
14358
  return screen.map((line, row) => {
13762
- if (row < minRow || row > maxRow || row < screenSelection.start.row || row > screenSelection.end.row || isImageLine(line)) return line;
14359
+ if (row < minRow || row > maxRow || row < screenSelection.start.row || row > screenSelection.end.row || this.isRenderableImageLine(line)) return line;
13763
14360
  const lineWidth = visibleWidth(line);
13764
14361
  const columns = this.getSelectionColumns(line, row, screenSelection, minColumn, maxColumn);
13765
14362
  if (columns.end <= columns.start) return line;
@@ -13782,7 +14379,7 @@ var TuiAltScreen = class extends TuiBase {
13782
14379
  const clip = box?.clip;
13783
14380
  if (!clip || clip.width <= 0 || clip.height <= 0) return screen;
13784
14381
  const row = clip.y + clip.height - 1;
13785
- if (row >= screen.length || isImageLine(screen[row] ?? "")) return screen;
14382
+ if (row >= screen.length || this.isRenderableImageLine(screen[row] ?? "")) return screen;
13786
14383
  const scrollbarColumn = box ? getScrollbarGeometry(box)?.column : void 0;
13787
14384
  const label = truncateToWidth(this.scrollToEndIndicator(), clip.width, "");
13788
14385
  const labelWidth = visibleWidth(label);
@@ -13809,6 +14406,7 @@ var TuiAltScreen = class extends TuiBase {
13809
14406
  const line = flashLines[row];
13810
14407
  const flashWidth = visibleWidth(line);
13811
14408
  if (flashWidth === 0) continue;
14409
+ if (this.isRenderableImageLine(result[row] ?? "")) continue;
13812
14410
  result[row] = compositeTuiLine(result[row] ?? "", line, width - flashWidth, flashWidth, width);
13813
14411
  }
13814
14412
  return result;
@@ -13818,9 +14416,12 @@ var TuiAltScreen = class extends TuiBase {
13818
14416
  const width = Math.max(1, this.terminal.columns);
13819
14417
  const height = Math.max(1, this.terminal.rows);
13820
14418
  const root = this.layoutRoot ?? this.implicitScrollView;
13821
- let nextLayout = renderLayoutFrame(root, width, height, () => this.requestRender());
13822
- if (this.refreshSearch(nextLayout)) nextLayout = renderLayoutFrame(root, width, height, () => this.requestRender());
13823
- let screen = nextLayout.lines.map((line) => line.replace(OSC133_ZONE_PREFIX, ""));
14419
+ let nextLayout = renderLayoutFrame(root, width, height, () => this.requestRender(), this.sixelScreen);
14420
+ if (this.refreshSearch(nextLayout)) nextLayout = renderLayoutFrame(root, width, height, () => this.requestRender(), this.sixelScreen);
14421
+ if (this.sixelScreen !== void 0) {
14422
+ if (this.sixelScreen.reconcileVisible(this, nextLayout.sixelDemands)) nextLayout = renderLayoutFrame(root, width, height, () => this.requestRender(), this.sixelScreen);
14423
+ }
14424
+ let screen = this.resolveFakeCursors(nextLayout.lines.map((line) => line.replace(OSC133_ZONE_PREFIX$1, "")));
13824
14425
  screen = this.applySearchHighlights(screen, nextLayout);
13825
14426
  screen = this.compositeScrollToEndIndicator(screen, nextLayout, width);
13826
14427
  screen = this.compositeOverlays(screen, width, height);
@@ -13828,14 +14429,25 @@ var TuiAltScreen = class extends TuiBase {
13828
14429
  if (this.overlaySelectionOrigin !== void 0 && !this.isOverlayTextSelectionRegionLive(this.overlaySelectionOrigin)) this.clearTextSelection();
13829
14430
  screen = this.applySelection(screen, nextLayout);
13830
14431
  screen = this.compositeFlashes(screen, width, height);
14432
+ const sixelRows = this.prepareSixelRows(screen);
14433
+ if (this.sixelScreen !== void 0) {
14434
+ const paintedDemands = nextLayout.sixelDemands.filter((demand) => !this.linesCoveredByOverlay(demand.physicalRow, demand.physicalRow + demand.visibleRows - 1, screen.length));
14435
+ if (paintedDemands.length !== nextLayout.sixelDemands.length) this.sixelScreen.reconcileVisible(this, paintedDemands);
14436
+ }
13831
14437
  const cursorPos = this.extractCursorPosition(screen, height);
13832
14438
  screen = this.applyLineResets(screen).map((line) => {
13833
- if (isImageLine(line) || visibleWidth(line) <= width) return line;
14439
+ if (this.isRenderableImageLine(line) || visibleWidth(line) <= width) return line;
13834
14440
  return sliceByColumn(line, 0, width, true);
13835
14441
  });
13836
14442
  const fullRedraw = this.previousScreen.length === 0 || this.previousScreenWidth !== width || this.previousScreenHeight !== height;
13837
14443
  const changedRows = screen.map((line, row) => line !== this.previousScreen[row]);
13838
- const imageAnchorsNeedRedraw = screen.some((line, row) => changedRows[row] && (isImageLine(line) || isImageLine(this.previousScreen[row] ?? "")));
14444
+ const imageAnchorsNeedRedraw = screen.some((line, row) => changedRows[row] && (this.isRenderableImageLine(line) || this.isRenderableImageLine(this.previousScreen[row] ?? "")));
14445
+ const sixelCoveredRows = /* @__PURE__ */ new Set();
14446
+ for (const declared of [this.previousSixelRows, sixelRows]) for (let row = 0; row < declared.length; row++) {
14447
+ const rows = declared[row] ?? 0;
14448
+ for (let offset = 0; offset < rows; offset++) sixelCoveredRows.add(row + offset);
14449
+ }
14450
+ const sixelNeedRedraw = changedRows.some((changed, row) => changed && (sixelCoveredRows.has(row) || (sixelRows[row] ?? 0) > 0));
13839
14451
  const isWezTerm = Boolean(process.env.WEZTERM_PANE) || process.env.TERM_PROGRAM?.toLowerCase() === "wezterm";
13840
14452
  const imageCellsNeedRedraw = !imageAnchorsNeedRedraw && isWezTerm && this.imageProtocol === "kitty" && changedRows.some(Boolean) && screen.some((line, row) => {
13841
14453
  const placementRows = getKittyImagePlacementRows(line);
@@ -13875,9 +14487,21 @@ var TuiAltScreen = class extends TuiBase {
13875
14487
  if (!isImageLine(preparedKittyScreen.lines[row] ?? "")) continue;
13876
14488
  buffer += `\x1b[${row + 1};1H${preparedKittyScreen.lines[row] ?? ""}`;
13877
14489
  }
13878
- } else for (let row = 0; row < height; row++) {
13879
- if (!fullRedraw && !imagesNeedRedraw && screen[row] === this.previousScreen[row]) continue;
13880
- buffer += `\x1b[${row + 1};1H\x1b[2K${preparedKittyScreen.lines[row] ?? ""}`;
14490
+ } else {
14491
+ if (sixelNeedRedraw) for (const row of [...sixelCoveredRows].sort((left, right) => left - right)) {
14492
+ if (row < 0 || row >= height) continue;
14493
+ buffer += `\x1b[${row + 1};1H\x1b[2K`;
14494
+ }
14495
+ for (let row = 0; row < height; row++) {
14496
+ const clearedBySixel = sixelNeedRedraw && sixelCoveredRows.has(row);
14497
+ if (!fullRedraw && !imagesNeedRedraw && !clearedBySixel && screen[row] === this.previousScreen[row]) continue;
14498
+ if ((sixelRows[row] ?? 0) > 0) continue;
14499
+ buffer += `\x1b[${row + 1};1H\x1b[2K${preparedKittyScreen.lines[row] ?? ""}`;
14500
+ }
14501
+ if (fullRedraw || sixelNeedRedraw) for (let row = 0; row < height; row++) {
14502
+ if ((sixelRows[row] ?? 0) === 0) continue;
14503
+ buffer += `\x1b[${row + 1};1H${screen[row]}`;
14504
+ }
13881
14505
  }
13882
14506
  if (cursorPos) {
13883
14507
  buffer += `\x1b[${cursorPos.row + 1};${Math.min(width, cursorPos.col) + 1}H`;
@@ -13885,13 +14509,17 @@ var TuiAltScreen = class extends TuiBase {
13885
14509
  } else buffer += "\x1B[?25l";
13886
14510
  buffer += END_SYNCHRONIZED_OUTPUT;
13887
14511
  this.terminal.write(buffer);
14512
+ this.commitSixelFrame(nextLayout, screen, changedRows, fullRedraw || sixelNeedRedraw);
13888
14513
  this.previousScreen = screen;
14514
+ this.previousSixelRows = sixelRows;
13889
14515
  this.previousScreenWidth = width;
13890
14516
  this.previousScreenHeight = height;
13891
14517
  this.currentLayout = nextLayout;
13892
14518
  this.onFramePainted?.();
13893
14519
  }
13894
14520
  };
14521
+ /** OSC 133 prompt markers at the start of a rendered line. Fullscreen uses them for prompt navigation. */
14522
+ const OSC133_ZONE_PREFIX = /^(?:\x1b\]133;[ABC](?:\x07|\x1b\\))+/;
13895
14523
  const KITTY_SEQUENCE_PREFIX = "\x1B_G";
13896
14524
  const MAX_RENDER_WRITE_CHARS = 1048576;
13897
14525
  const EMPTY_IMAGE_IDS = [];
@@ -13989,12 +14617,36 @@ var TuiMainScreen = class extends TuiBase {
13989
14617
  /** Per-line kitty image ids of the previous frame, aligned with previousRawLines. */
13990
14618
  previousLineImageIds = [];
13991
14619
  previousKittyImageIds = /* @__PURE__ */ new Set();
14620
+ /**
14621
+ * Declared image rows of the previous frame, aligned with
14622
+ * {@link previousLines}: a Kitty `r=`/registered placement row count, or a
14623
+ * trusted SIXEL footprint. Cached instead of re-deriving from the line,
14624
+ * because a raster whose component was disposed is no longer registered —
14625
+ * the OLD block must still be erased (X073).
14626
+ */
14627
+ previousLineImageRows = [];
14628
+ /**
14629
+ * Per-line TRUSTED SIXEL footprint height of the previous frame (0 = no
14630
+ * SIXEL block). Unlike the Kitty row count this is exact, so it never has to
14631
+ * be re-derived by scanning blank body rows — a scan would collapse under an
14632
+ * overlay or a text row that landed inside the block. (X073.)
14633
+ */
14634
+ previousLineSixelRows = [];
13992
14635
  previousWidth = 0;
13993
14636
  previousHeight = 0;
13994
14637
  cursorRow = 0;
13995
14638
  hardwareCursorRow = 0;
13996
14639
  maxLinesRendered = 0;
13997
14640
  previousViewportTop = 0;
14641
+ /** Per-row token -> DCS the current frame materialized (X073). */
14642
+ sixelFrameRasters = /* @__PURE__ */ new Map();
14643
+ /**
14644
+ * @param sixelScreen - the Client-local SIXEL trust port (X072). Absent for
14645
+ * every non-SIXEL terminal, and then this screen is byte-for-byte upstream.
14646
+ */
14647
+ constructor(terminal, showHardwareCursor, logDirectory, sixelScreen) {
14648
+ super(terminal, showHardwareCursor, logDirectory, sixelScreen);
14649
+ }
13998
14650
  captureRenderState() {
13999
14651
  return {
14000
14652
  previousLines: [...this.previousLines],
@@ -14007,9 +14659,11 @@ var TuiMainScreen = class extends TuiBase {
14007
14659
  };
14008
14660
  }
14009
14661
  restoreRenderState(state) {
14010
- this.previousLines = state.previousLines.map((line) => isImageLine(line) ? "" : line);
14662
+ this.previousLines = state.previousLines.map((line) => this.isRenderableImageLine(line) ? "" : line);
14011
14663
  this.previousRawLines = [];
14012
14664
  this.previousLineImageIds = [];
14665
+ this.previousLineImageRows = [];
14666
+ this.previousLineSixelRows = [];
14013
14667
  this.previousKittyImageIds = /* @__PURE__ */ new Set();
14014
14668
  this.previousWidth = state.previousWidth;
14015
14669
  this.previousHeight = state.previousHeight;
@@ -14022,6 +14676,8 @@ var TuiMainScreen = class extends TuiBase {
14022
14676
  this.previousLines = [];
14023
14677
  this.previousRawLines = [];
14024
14678
  this.previousLineImageIds = [];
14679
+ this.previousLineImageRows = [];
14680
+ this.previousLineSixelRows = [];
14025
14681
  this.previousWidth = -1;
14026
14682
  this.previousHeight = -1;
14027
14683
  this.cursorRow = 0;
@@ -14047,33 +14703,191 @@ var TuiMainScreen = class extends TuiBase {
14047
14703
  for (const id of ids) buffer += deleteKittyImage(id);
14048
14704
  return buffer;
14049
14705
  }
14050
- getKittyImageReservedRows(lines, index, maxIndex = lines.length - 1) {
14051
- const rows = extractKittyImageRows(lines[index] ?? "");
14706
+ /**
14707
+ * Project the frame's candidate markers into what this Screen may write.
14708
+ *
14709
+ * The component tree only ever emits an inert candidate marker per block; the
14710
+ * final viewport decides which occurrences are granted residency. Rows above
14711
+ * the viewport keep their previous physical line when the SAME occurrence is
14712
+ * still there: a residency-only change must not rewrite committed scrollback
14713
+ * (a rewrite above the viewport would force `fullRender(true)` and `3J`).
14714
+ */
14715
+ projectSixelCandidates(rawLines, height, viewportTop, width, reconcile) {
14716
+ const port = this.sixelScreen;
14717
+ const lines = [...rawLines];
14718
+ const rasters = /* @__PURE__ */ new Map();
14719
+ const preserved = /* @__PURE__ */ new Set();
14720
+ if (port === void 0) return {
14721
+ lines,
14722
+ rasters,
14723
+ preserved,
14724
+ recompose: false
14725
+ };
14726
+ const visible = [];
14727
+ for (let row = viewportTop; row < Math.min(rawLines.length, viewportTop + height); row += 1) {
14728
+ const info = port.candidate(rawLines[row] ?? "");
14729
+ if (info === void 0) continue;
14730
+ const visibleRows = Math.min(info.layoutRows, viewportTop + height - row);
14731
+ if (visibleRows <= 0) continue;
14732
+ visible.push({
14733
+ row,
14734
+ fallback: info.fallback,
14735
+ cropTopRows: 0,
14736
+ visibleRows
14737
+ });
14738
+ }
14739
+ visible.sort((left, right) => right.row - left.row);
14740
+ if (reconcile) {
14741
+ if (port.reconcileVisible(this, visible.map((entry) => ({
14742
+ line: rawLines[entry.row],
14743
+ cropTopRows: entry.cropTopRows,
14744
+ visibleRows: entry.visibleRows,
14745
+ physicalRow: entry.row
14746
+ })))) return {
14747
+ lines,
14748
+ rasters,
14749
+ preserved,
14750
+ recompose: true
14751
+ };
14752
+ }
14753
+ for (const entry of visible) {
14754
+ const token = rawLines[entry.row];
14755
+ const dcs = port.materialize(token, entry.cropTopRows, entry.visibleRows);
14756
+ if (dcs === void 0) {
14757
+ lines[entry.row] = entry.fallback;
14758
+ continue;
14759
+ }
14760
+ lines[entry.row] = dcs;
14761
+ const footprint = port.footprint(dcs);
14762
+ rasters.set(entry.row, {
14763
+ line: token,
14764
+ dcs,
14765
+ cropTopRows: entry.cropTopRows,
14766
+ visibleRows: footprint?.rows ?? entry.visibleRows
14767
+ });
14768
+ }
14769
+ for (let row = 0; row < viewportTop && row < rawLines.length; row += 1) {
14770
+ const token = rawLines[row] ?? "";
14771
+ const info = port.candidate(token);
14772
+ if (info === void 0) continue;
14773
+ const previous = this.previousLines[row] ?? "";
14774
+ if (this.previousRawLines[row] === token && this.sixelFootprint(previous) !== void 0) {
14775
+ lines[row] = previous;
14776
+ preserved.add(row);
14777
+ } else if (this.previousRawLines[row] === token) {
14778
+ let fallback = info.fallback;
14779
+ if (visibleWidth(fallback) > width) fallback = sliceByColumn(fallback, 0, width, true);
14780
+ fallback = normalizeTerminalOutput(fallback) + SEGMENT_RESET;
14781
+ this.previousLines[row] = fallback;
14782
+ this.previousLineSixelRows[row] = 0;
14783
+ this.previousLineImageRows[row] = 0;
14784
+ this.previousLineImageIds[row] = [];
14785
+ lines[row] = fallback;
14786
+ preserved.add(row);
14787
+ } else lines[row] = info.fallback;
14788
+ }
14789
+ return {
14790
+ lines,
14791
+ rasters,
14792
+ preserved,
14793
+ recompose: false
14794
+ };
14795
+ }
14796
+ /**
14797
+ * Report the frame's physical raster set to the owner after a real write.
14798
+ *
14799
+ * `emitted` rasters are the ones this frame materialized; a row the diff kept
14800
+ * (byte-identical to the previous frame) still shows its old pixels and pins
14801
+ * its occurrence. Rows above the viewport are never reported: their pixels are
14802
+ * native scrollback, not a frame reference.
14803
+ */
14804
+ commitSixelFrame(frameLines, viewportTop, height) {
14805
+ const port = this.sixelScreen;
14806
+ if (port === void 0) return;
14807
+ const retained = [];
14808
+ for (const row of [...this.sixelFrameRasters.keys()].sort((left, right) => right - left)) {
14809
+ const raster = this.sixelFrameRasters.get(row);
14810
+ if (row < viewportTop || row >= viewportTop + height) continue;
14811
+ retained.push({
14812
+ ...raster,
14813
+ emitted: true
14814
+ });
14815
+ }
14816
+ const last = Math.min(frameLines.length, viewportTop + height) - 1;
14817
+ for (let row = last; row >= viewportTop; row -= 1) {
14818
+ if (this.sixelFrameRasters.has(row)) continue;
14819
+ const token = this.previousRawLines[row];
14820
+ if (token === void 0 || port.candidate(token) === void 0) continue;
14821
+ const previous = this.previousLines[row];
14822
+ if (previous === void 0 || previous !== frameLines[row]) continue;
14823
+ const footprint = port.footprint(previous);
14824
+ if (footprint === void 0) continue;
14825
+ retained.push({
14826
+ line: token,
14827
+ dcs: previous,
14828
+ cropTopRows: 0,
14829
+ visibleRows: footprint.rows,
14830
+ emitted: false
14831
+ });
14832
+ }
14833
+ this.sixelFrameRasters = /* @__PURE__ */ new Map();
14834
+ port.framePainted(this, retained);
14835
+ }
14836
+ /**
14837
+ * The image rows one line DECLARES: a Kitty `r=`/registered placement, or a
14838
+ * trusted SIXEL footprint. `0` for a non-image line, so callers can decide
14839
+ * "is an image" and "how tall" from one number.
14840
+ */
14841
+ declaredImageRows(line) {
14842
+ const candidate = this.sixelScreen?.candidate(line);
14843
+ if (candidate !== void 0) return candidate.layoutRows;
14844
+ const footprint = this.sixelFootprint(line);
14845
+ if (footprint !== void 0) return footprint.rows;
14846
+ return isImageLine(line) ? extractKittyImageRows(line) : 0;
14847
+ }
14848
+ /** The trusted SIXEL footprint height of one line, or 0 when it is not a
14849
+ * registered raster. */
14850
+ sixelBlockRows(line) {
14851
+ const candidate = this.sixelScreen?.candidate(line);
14852
+ if (candidate !== void 0) return candidate.layoutRows;
14853
+ return this.sixelFootprint(line)?.rows ?? 0;
14854
+ }
14855
+ /**
14856
+ * The rows an image block really occupies in `lines`, starting at `index`.
14857
+ *
14858
+ * `declared` is the per-line declared row count of the SAME frame (cached for
14859
+ * the previous frame), so a raster that is no longer registered still
14860
+ * reports its real old height. The scan stops at the first body row another
14861
+ * image owns or at the first row with cell content.
14862
+ */
14863
+ getImageReservedRows(lines, declared, sixel, index, maxIndex = lines.length - 1) {
14864
+ const rows = declared[index] ?? 0;
14052
14865
  if (rows <= 1) return 1;
14053
14866
  const maxRows = Math.min(rows, maxIndex - index + 1, lines.length - index);
14867
+ if ((sixel[index] ?? 0) > 0) return maxRows;
14054
14868
  let reservedRows = 1;
14055
14869
  while (reservedRows < maxRows) {
14056
14870
  const line = lines[index + reservedRows] ?? "";
14057
- if (isImageLine(line) || visibleWidth(line) > 0) break;
14871
+ if ((declared[index + reservedRows] ?? 0) > 0 || visibleWidth(line) > 0) break;
14058
14872
  reservedRows++;
14059
14873
  }
14060
14874
  return reservedRows;
14061
14875
  }
14062
- expandChangedRangeForKittyImages(firstChanged, lastChanged, newLines, newLineImageIds) {
14876
+ expandChangedRangeForImages(firstChanged, lastChanged, newLines, newLineImageRows, newLineSixelRows) {
14063
14877
  let expandedFirstChanged = firstChanged;
14064
14878
  let expandedLastChanged = lastChanged;
14065
- const expandForLines = (lines, lineImageIds) => {
14879
+ const expandForLines = (lines, declared, sixel) => {
14066
14880
  for (let i = 0; i < lines.length; i++) {
14067
- if ((lineImageIds[i] ?? EMPTY_IMAGE_IDS).length === 0) continue;
14068
- const blockEnd = i + this.getKittyImageReservedRows(lines, i) - 1;
14881
+ if ((declared[i] ?? 0) === 0) continue;
14882
+ const blockEnd = i + this.getImageReservedRows(lines, declared, sixel, i) - 1;
14069
14883
  if (i >= firstChanged || i <= lastChanged && blockEnd >= firstChanged) {
14070
14884
  expandedFirstChanged = Math.min(expandedFirstChanged, i);
14071
14885
  expandedLastChanged = Math.max(expandedLastChanged, blockEnd);
14072
14886
  }
14073
14887
  }
14074
14888
  };
14075
- expandForLines(this.previousLines, this.previousLineImageIds);
14076
- expandForLines(newLines, newLineImageIds);
14889
+ expandForLines(this.previousLines, this.previousLineImageRows, this.previousLineSixelRows);
14890
+ expandForLines(newLines, newLineImageRows, newLineSixelRows);
14077
14891
  return {
14078
14892
  firstChanged: expandedFirstChanged,
14079
14893
  lastChanged: expandedLastChanged
@@ -14086,6 +14900,73 @@ var TuiMainScreen = class extends TuiBase {
14086
14900
  for (let i = firstChanged; i <= maxLine; i++) for (const id of this.previousLineImageIds[i] ?? EMPTY_IMAGE_IDS) ids.add(id);
14087
14901
  return this.deleteKittyImages(ids);
14088
14902
  }
14903
+ /**
14904
+ * Drop the DCS of every trusted SIXEL block that a visible overlay paints
14905
+ * over (X073).
14906
+ *
14907
+ * One raster is one command covering its whole footprint, so "clear only the
14908
+ * row the overlay touched" is impossible: the pixels would either cover the
14909
+ * overlay text or leave a ghost. The block therefore yields this frame — the
14910
+ * component's own identity row above it still names the attachment — and the
14911
+ * next frame after the overlay closes restores it, because the anchor line
14912
+ * changes and the block re-enters the changed range.
14913
+ */
14914
+ suppressOverlayCoveredSixelBlocks(lines) {
14915
+ for (let i = 0; i < lines.length; i++) {
14916
+ const rows = this.sixelBlockRows(lines[i] ?? "");
14917
+ if (rows === 0) continue;
14918
+ if (!this.linesCoveredByOverlay(i, i + rows - 1, lines.length)) continue;
14919
+ lines[i] = "";
14920
+ }
14921
+ }
14922
+ /**
14923
+ * Write every deferred trusted SIXEL anchor at its own absolute row, then
14924
+ * leave the cursor on `finalCursorRow`.
14925
+ *
14926
+ * `CSI 999A` (cursor up, clamped at the top margin) is the one deterministic
14927
+ * origin the main screen has: it cannot scroll and it lands on the physical
14928
+ * top row, which this screen's bookkeeping maps to buffer row `viewportTop`.
14929
+ * From there a bounded `CSI nB` reaches any visible row exactly. Each DCS is
14930
+ * wrapped in DECSC/DECRC because its post-command cursor position is
14931
+ * terminal-defined, never assumed to be zero.
14932
+ *
14933
+ * Returns false when an anchor is not inside the painted viewport; the caller
14934
+ * then falls back to a full redraw instead of painting outside it.
14935
+ */
14936
+ writeDeferredSixelAnchors(output, anchors, lines, viewportTop, height, finalCursorRow) {
14937
+ for (const anchor of anchors) {
14938
+ const screenRow = anchor - viewportTop;
14939
+ if (screenRow < 0 || screenRow >= height) return false;
14940
+ output.append("\x1B[999A");
14941
+ if (screenRow > 0) output.append(`\x1b[${screenRow}B`);
14942
+ output.append("\x1B7");
14943
+ output.append(lines[anchor] ?? "");
14944
+ output.append("\x1B8");
14945
+ }
14946
+ const endScreenRow = Math.max(0, Math.min(height - 1, finalCursorRow - viewportTop));
14947
+ output.append("\x1B[999A");
14948
+ if (endScreenRow > 0) output.append(`\x1b[${endScreenRow}B`);
14949
+ output.append("\r");
14950
+ return true;
14951
+ }
14952
+ /**
14953
+ * Write one image anchor at the cursor's current row.
14954
+ *
14955
+ * A Kitty placement leaves the cursor where it was; a SIXEL DCS does not, and
14956
+ * its post-command position is terminal-defined. The anchor is therefore
14957
+ * SAVED before the command and RESTORED after it (DECSC/DECRC), and the
14958
+ * caller then moves the cursor explicitly — "the DCS left it at 0" is never
14959
+ * assumed. (dsh-pi-tui divergence X073.)
14960
+ */
14961
+ appendImageCommand(output, line, sixel) {
14962
+ if (!sixel) {
14963
+ output.append(line);
14964
+ return;
14965
+ }
14966
+ output.append("\x1B7");
14967
+ output.append(line);
14968
+ output.append("\x1B8");
14969
+ }
14089
14970
  doRender() {
14090
14971
  if (this.stopped) return;
14091
14972
  const width = this.terminal.columns;
@@ -14100,29 +14981,46 @@ var TuiMainScreen = class extends TuiBase {
14100
14981
  const currentScreenRow = hardwareCursorRow - prevViewportTop;
14101
14982
  return targetRow - viewportTop - currentScreenRow;
14102
14983
  };
14103
- let newLines = this.render(width);
14104
- if (this.hasOverlayEntries) newLines = this.compositeOverlays(newLines, width, height);
14984
+ let rawLines = this.resolveFakeCursors(this.render(width).map((line) => line.replace(OSC133_ZONE_PREFIX, "")));
14985
+ if (this.hasOverlayEntries) {
14986
+ rawLines = this.compositeOverlays(rawLines, width, height);
14987
+ this.suppressOverlayCoveredSixelBlocks(rawLines);
14988
+ }
14989
+ const frameViewportTop = Math.max(0, rawLines.length - height);
14990
+ let projection = this.projectSixelCandidates(rawLines, height, frameViewportTop, width, true);
14991
+ if (projection.recompose) projection = this.projectSixelCandidates(rawLines, height, frameViewportTop, width, false);
14992
+ this.sixelFrameRasters = projection.rasters;
14993
+ const preservedRows = projection.preserved;
14994
+ let newLines = projection.lines;
14105
14995
  const cursorPos = this.extractCursorPosition(newLines, height);
14106
- const rawLines = newLines;
14107
14996
  const reuseProcessed = !widthChanged && this.previousRawLines.length > 0;
14108
- const processedLines = new Array(rawLines.length);
14109
- const lineImageIds = new Array(rawLines.length);
14110
- for (let i = 0; i < rawLines.length; i++) {
14111
- const rawLine = rawLines[i];
14112
- if (reuseProcessed && rawLine === this.previousRawLines[i]) {
14997
+ const processedLines = new Array(newLines.length);
14998
+ const lineImageIds = new Array(newLines.length);
14999
+ const lineImageRows = new Array(newLines.length);
15000
+ const lineSixelRows = new Array(newLines.length);
15001
+ for (let i = 0; i < newLines.length; i++) {
15002
+ const marker = rawLines[i] ?? "";
15003
+ const isCandidate = this.sixelScreen?.candidate(marker) !== void 0;
15004
+ if (preservedRows.has(i) || !isCandidate && reuseProcessed && marker === this.previousRawLines[i]) {
14113
15005
  processedLines[i] = this.previousLines[i];
14114
15006
  lineImageIds[i] = this.previousLineImageIds[i];
15007
+ lineImageRows[i] = this.previousLineImageRows[i];
15008
+ lineSixelRows[i] = this.previousLineSixelRows[i];
14115
15009
  continue;
14116
15010
  }
14117
- let line = rawLine;
15011
+ let line = newLines[i];
14118
15012
  let imageIds = EMPTY_IMAGE_IDS;
14119
- if (isImageLine(line)) imageIds = extractKittyImageIds(line);
15013
+ const sixelRows = this.sixelBlockRows(line);
15014
+ const declaredImageRows = this.declaredImageRows(line);
15015
+ if (declaredImageRows > 0) imageIds = extractKittyImageIds(line);
14120
15016
  else {
14121
15017
  if ((asciiVisibleWidthEarlyExit(line, width) ?? visibleWidth(line)) > width) line = sliceByColumn(line, 0, width, true);
14122
15018
  line = normalizeTerminalOutput(line) + SEGMENT_RESET;
14123
15019
  }
14124
15020
  processedLines[i] = line;
14125
15021
  lineImageIds[i] = imageIds;
15022
+ lineImageRows[i] = declaredImageRows;
15023
+ lineSixelRows[i] = sixelRows;
14126
15024
  }
14127
15025
  newLines = processedLines;
14128
15026
  const fullRender = (clear) => {
@@ -14136,19 +15034,21 @@ var TuiMainScreen = class extends TuiBase {
14136
15034
  for (let i = 0; i < newLines.length; i++) {
14137
15035
  if (i > 0) output.append("\r\n");
14138
15036
  const line = newLines[i];
14139
- const imageReservedRows = isImageLine(line) ? this.getKittyImageReservedRows(newLines, i) : 1;
15037
+ const isSixel = (lineSixelRows[i] ?? 0) > 0;
15038
+ const imageReservedRows = isSixel || isImageLine(line) ? this.getImageReservedRows(newLines, lineImageRows, lineSixelRows, i) : 1;
14140
15039
  if (imageReservedRows > 1 && imageReservedRows <= height) {
14141
15040
  for (let row = 1; row < imageReservedRows; row++) output.append("\r\n");
14142
15041
  output.append(`\x1b[${imageReservedRows - 1}A`);
14143
- output.append(line);
15042
+ this.appendImageCommand(output, line, isSixel);
14144
15043
  output.append(`\x1b[${imageReservedRows - 1}B`);
14145
15044
  i += imageReservedRows - 1;
14146
15045
  continue;
14147
15046
  }
14148
- output.append(line);
15047
+ this.appendImageCommand(output, line, isSixel);
14149
15048
  }
14150
15049
  output.append("\x1B[?2026l");
14151
15050
  output.flush();
15051
+ this.commitSixelFrame(newLines, frameViewportTop, height);
14152
15052
  this.cursorRow = Math.max(0, newLines.length - 1);
14153
15053
  this.hardwareCursorRow = this.cursorRow;
14154
15054
  if (clear) this.maxLinesRendered = newLines.length;
@@ -14159,6 +15059,8 @@ var TuiMainScreen = class extends TuiBase {
14159
15059
  this.previousLines = newLines;
14160
15060
  this.previousRawLines = rawLines;
14161
15061
  this.previousLineImageIds = lineImageIds;
15062
+ this.previousLineImageRows = lineImageRows;
15063
+ this.previousLineSixelRows = lineSixelRows;
14162
15064
  this.previousKittyImageIds = this.unionKittyImageIds(lineImageIds);
14163
15065
  this.previousWidth = width;
14164
15066
  this.previousHeight = height;
@@ -14204,7 +15106,7 @@ var TuiMainScreen = class extends TuiBase {
14204
15106
  lastChanged = newLines.length - 1;
14205
15107
  }
14206
15108
  if (firstChanged !== -1) {
14207
- const expandedRange = this.expandChangedRangeForKittyImages(firstChanged, lastChanged, newLines, lineImageIds);
15109
+ const expandedRange = this.expandChangedRangeForImages(firstChanged, lastChanged, newLines, lineImageRows, lineSixelRows);
14208
15110
  firstChanged = expandedRange.firstChanged;
14209
15111
  lastChanged = expandedRange.lastChanged;
14210
15112
  }
@@ -14215,6 +15117,8 @@ var TuiMainScreen = class extends TuiBase {
14215
15117
  this.previousHeight = height;
14216
15118
  this.previousRawLines = rawLines;
14217
15119
  this.previousLineImageIds = lineImageIds;
15120
+ this.previousLineImageRows = lineImageRows;
15121
+ this.previousLineSixelRows = lineSixelRows;
14218
15122
  return;
14219
15123
  }
14220
15124
  if (firstChanged >= newLines.length) {
@@ -14248,6 +15152,7 @@ var TuiMainScreen = class extends TuiBase {
14248
15152
  if (moveBack > 0) output.append(`\x1b[${moveBack}A`);
14249
15153
  output.append("\x1B[?2026l");
14250
15154
  output.flush();
15155
+ this.commitSixelFrame(newLines, frameViewportTop, height);
14251
15156
  this.cursorRow = targetRow;
14252
15157
  this.hardwareCursorRow = targetRow;
14253
15158
  }
@@ -14255,6 +15160,8 @@ var TuiMainScreen = class extends TuiBase {
14255
15160
  this.previousLines = newLines;
14256
15161
  this.previousRawLines = rawLines;
14257
15162
  this.previousLineImageIds = lineImageIds;
15163
+ this.previousLineImageRows = lineImageRows;
15164
+ this.previousLineSixelRows = lineSixelRows;
14258
15165
  this.previousKittyImageIds = this.unionKittyImageIds(lineImageIds);
14259
15166
  this.previousWidth = width;
14260
15167
  this.previousHeight = height;
@@ -14286,22 +15193,25 @@ var TuiMainScreen = class extends TuiBase {
14286
15193
  else if (lineDiff < 0) output.append(`\x1b[${-lineDiff}A`);
14287
15194
  output.append(appendStart ? "\r\n" : "\r");
14288
15195
  const renderEnd = Math.min(lastChanged, newLines.length - 1);
15196
+ const deferredSixelAnchors = [];
14289
15197
  for (let i = firstChanged; i <= renderEnd; i++) {
14290
15198
  if (i > firstChanged) output.append("\r\n");
14291
15199
  const line = newLines[i];
14292
- const isImage = isImageLine(line);
14293
- const imageReservedRows = isImage ? this.getKittyImageReservedRows(newLines, i, renderEnd) : 1;
15200
+ const isSixel = (lineSixelRows[i] ?? 0) > 0;
15201
+ const isImage = isSixel || isImageLine(line);
15202
+ const imageReservedRows = isImage ? this.getImageReservedRows(newLines, lineImageRows, lineSixelRows, i, renderEnd) : 1;
14294
15203
  if (imageReservedRows > 1) {
14295
15204
  const imageStartScreenRow = i - viewportTop;
14296
15205
  if (imageStartScreenRow < 0 || imageStartScreenRow + imageReservedRows > height) {
14297
- logRedraw(`kitty image pre-clear would scroll (${imageStartScreenRow} + ${imageReservedRows} > ${height})`);
15206
+ logRedraw(`image pre-clear would scroll (${imageStartScreenRow} + ${imageReservedRows} > ${height})`);
14298
15207
  fullRender(true);
14299
15208
  return;
14300
15209
  }
14301
15210
  output.append("\x1B[2K");
14302
15211
  for (let row = 1; row < imageReservedRows; row++) output.append("\r\n\x1B[2K");
14303
15212
  output.append(`\x1b[${imageReservedRows - 1}A`);
14304
- output.append(line);
15213
+ if (isSixel) deferredSixelAnchors.push(i);
15214
+ else output.append(line);
14305
15215
  output.append(`\x1b[${imageReservedRows - 1}B`);
14306
15216
  i += imageReservedRows - 1;
14307
15217
  continue;
@@ -14331,7 +15241,8 @@ var TuiMainScreen = class extends TuiBase {
14331
15241
  ].join("\n");
14332
15242
  throw new Error(errorMsg);
14333
15243
  }
14334
- output.append(line);
15244
+ if (isSixel) deferredSixelAnchors.push(i);
15245
+ else output.append(line);
14335
15246
  }
14336
15247
  let finalCursorRow = renderEnd;
14337
15248
  if (this.previousLines.length > newLines.length) {
@@ -14344,6 +15255,13 @@ var TuiMainScreen = class extends TuiBase {
14344
15255
  for (let i = newLines.length; i < this.previousLines.length; i++) output.append("\r\n\x1B[2K");
14345
15256
  output.append(`\x1b[${extraLines}A`);
14346
15257
  }
15258
+ if (deferredSixelAnchors.length > 0) {
15259
+ if (!this.writeDeferredSixelAnchors(output, deferredSixelAnchors, newLines, viewportTop, height, finalCursorRow)) {
15260
+ logRedraw("deferred SIXEL anchor is not inside the painted viewport");
15261
+ fullRender(true);
15262
+ return;
15263
+ }
15264
+ }
14347
15265
  output.append("\x1B[?2026l");
14348
15266
  if (process.env.PI_TUI_DEBUG === "1") {
14349
15267
  const debugDir = "/tmp/tui";
@@ -14374,6 +15292,7 @@ var TuiMainScreen = class extends TuiBase {
14374
15292
  fs.writeFileSync(debugPath, debugData);
14375
15293
  }
14376
15294
  output.flush();
15295
+ this.commitSixelFrame(newLines, frameViewportTop, height);
14377
15296
  this.cursorRow = Math.max(0, newLines.length - 1);
14378
15297
  this.hardwareCursorRow = finalCursorRow;
14379
15298
  this.maxLinesRendered = Math.max(this.maxLinesRendered, newLines.length);
@@ -14382,6 +15301,8 @@ var TuiMainScreen = class extends TuiBase {
14382
15301
  this.previousLines = newLines;
14383
15302
  this.previousRawLines = rawLines;
14384
15303
  this.previousLineImageIds = lineImageIds;
15304
+ this.previousLineImageRows = lineImageRows;
15305
+ this.previousLineSixelRows = lineSixelRows;
14385
15306
  this.previousKittyImageIds = this.unionKittyImageIds(lineImageIds);
14386
15307
  this.previousWidth = width;
14387
15308
  this.previousHeight = height;
@@ -15064,6 +15985,14 @@ const APP_KEYBINDINGS = {
15064
15985
  scope: "question",
15065
15986
  configurable: false
15066
15987
  },
15988
+ "interaction.navigateWorkspace": {
15989
+ id: "interaction.navigateWorkspace",
15990
+ defaultKeys: ["alt+w"],
15991
+ description: "Open the Session Workspace without answering the pending interaction",
15992
+ category: "Question",
15993
+ scope: "overlay",
15994
+ configurable: false
15995
+ },
15067
15996
  "tasks.open": {
15068
15997
  id: "tasks.open",
15069
15998
  defaultKeys: ["enter"],
@@ -15913,11 +16842,14 @@ const SESSIONLESS_COMMANDS = /* @__PURE__ */ new Set([
15913
16842
  "preset",
15914
16843
  "keybindings",
15915
16844
  "plugins",
16845
+ "web",
15916
16846
  "quit",
15917
16847
  "statusline",
15918
16848
  "status",
15919
16849
  "view-image",
15920
- "deliverables"
16850
+ "deliverables",
16851
+ "reload-client",
16852
+ "schedule"
15921
16853
  ]);
15922
16854
  /**
15923
16855
  * The LOCAL-execute command set (PR5 v2 §1C-6 narrows its semantic role):
@@ -15976,9 +16908,12 @@ const LOCAL_COMMANDS = /* @__PURE__ */ new Set([
15976
16908
  "title",
15977
16909
  "transcript",
15978
16910
  "yolo",
16911
+ "web",
15979
16912
  "view-image",
15980
16913
  "deliverables",
15981
- "statusline"
16914
+ "statusline",
16915
+ "reload-client",
16916
+ "schedule"
15982
16917
  ]);
15983
16918
  /**
15984
16919
  * The STATIC host-owned command catalog (P1-04): the ownership sets
@@ -16158,6 +17093,47 @@ function shouldConsumeAdvertisedMiss(execution, wasAdvertised) {
16158
17093
  function isPlainExitPrompt(text) {
16159
17094
  return text.trim() === "exit";
16160
17095
  }
17096
+ /**
17097
+ * The TUI-local commands whose OWN handler performs no persistent Host write
17098
+ * (they read/browse/stage locally, open a read-only panel, or are the reload
17099
+ * command itself). Their execution never holds the accepted-command reload
17100
+ * lifetime — a `/reload` catalog/settings refresh or `/exit` must not block a
17101
+ * manual Client reload.
17102
+ *
17103
+ * Every OTHER local command is treated as a potential persisted writer
17104
+ * (fail-safe): its accepted execution — including the asynchronous preparation
17105
+ * that precedes a configuration write — keeps the Client reload gate closed
17106
+ * until the handler settles. A new write-capable local command is therefore
17107
+ * protected by default instead of requiring an addition to this set.
17108
+ */
17109
+ const READ_ONLY_LOCAL_COMMANDS = /* @__PURE__ */ new Set([
17110
+ "reload-client",
17111
+ "reload",
17112
+ "exit",
17113
+ "quit",
17114
+ "help",
17115
+ "keybindings",
17116
+ "copy",
17117
+ "attach",
17118
+ "image",
17119
+ "export",
17120
+ "transcript",
17121
+ "deliverables",
17122
+ "view-image",
17123
+ "sessions",
17124
+ "resume",
17125
+ "search",
17126
+ "tasks"
17127
+ ]);
17128
+ /**
17129
+ * Whether one TUI-local command may perform a persistent Host write during its
17130
+ * own handler execution. Fail-safe: anything not explicitly read-only is
17131
+ * treated as a possible writer.
17132
+ * @param name - the local command name (bare token).
17133
+ */
17134
+ function localCommandMayWrite(name) {
17135
+ return !READ_ONLY_LOCAL_COMMANDS.has(name);
17136
+ }
16161
17137
  //#endregion
16162
17138
  //#region src/extension/internal/batcher.ts
16163
17139
  /** Coalescing invalidate dispatcher. `flush()` is idempotent per tick. */
@@ -19186,14 +20162,6 @@ var PiTuiExtensionServiceImpl = class PiTuiExtensionServiceImpl extends Service
19186
20162
  };
19187
20163
  //#endregion
19188
20164
  //#region src/extensions.ts
19189
- var extensions_exports = /* @__PURE__ */ __exportAll({
19190
- API_VERSION: () => 2,
19191
- PI_TUI_EXTENSIONS_SERVICE: () => PI_TUI_EXTENSIONS_SERVICE,
19192
- apply: () => apply,
19193
- describeKey: () => describeKey,
19194
- inject: () => inject,
19195
- name: () => name
19196
- });
19197
20165
  /** Stable Cordis plugin name for the extension host row. */
19198
20166
  const name = "pi-tui-extension-host";
19199
20167
  /** The host mounts only when the TUI startup flags were parsed (same gate
@@ -19222,4 +20190,4 @@ function apply(ctx) {
19222
20190
  new PiTuiExtensionServiceImpl(ctx, packageVersion(), () => {}, HOST_COMMAND_CATALOG);
19223
20191
  }
19224
20192
  //#endregion
19225
- export { fuzzyFilter as $, isValidKeyId as A, MouseRegion as B, isTerminalAmbiguousKeyId as C, canonicalizeKeyId as D, VIEWER_BLOCKED_PARENT_ACTIONS as E, HStack as F, Text as G, ScrollView as H, Image as I, VStack as J, TuiAltScreen as K, Input as L, CombinedAutocompleteProvider as M, Container as N, isRuntimeBindableKeyId as O, Editor as P, findAltScreenSearchMatches as Q, Key as R, isPhysicalEscapeAction as S, APP_KEYBINDINGS as T, SettingsList as U, ProcessTerminal as V, Spacer as W, decodePrintableKey as X, decodeKittyPrintable as Y, dispatchMouseEvent as Z, normalizeSkillInvocation as _, parseFooterLayout as _t, PI_TUI_EXTENSIONS_SERVICE as a, isFocusable as at, DEFAULT_LEADER_TIMEOUT_MS as b, InvalidateBatcher as c, matchesKey as ct, SESSIONLESS_COMMANDS as d, sliceByColumn as dt, getCapabilities as et, classifyCommandLine as f, stripTerminalSequences as ft, isPlainExitPrompt as g, isFooterLayout as gt, isLocalCommandLine as h, wrapTextWithAnsi as ht, name as i, imageFallback as it, AltScreenSearchIndex as j, isTextProducingKeyId as k, HOST_COMMAND_CATALOG as l, parseKey as lt, isBareCommandLine as m, visibleWidth as mt, extensions_exports as n, getGraphemeSegmenter as nt, API_VERSION as o, isKeyRelease as ot, commandIsLocalForAttachments as p, truncateToWidth as pt, TuiMainScreen as q, inject as r, getKeybindings as rt, describeKey as s, isKeyRepeat as st, apply as t, getCellDimensions as tt, LOCAL_COMMANDS as u, registerKittyImageMetadata as ut, shouldConsumeAdvertisedMiss as v, resolveCommandFooterFallback as vt, parseUserKeybindings as w, isEditorSubmitPreSubmitKey as x, normalizeInputEvent as y, stripControlChars as yt, Markdown as z };
20193
+ export { findAltScreenSearchMatches as $, isValidKeyId as A, Markdown as B, isTerminalAmbiguousKeyId as C, stripControlChars as Ct, canonicalizeKeyId as D, VIEWER_BLOCKED_PARENT_ACTIONS as E, Editor as F, Spacer as G, ProcessTerminal as H, HStack as I, TuiMainScreen as J, Text as K, Image as L, CURSOR_MARKER as M, CombinedAutocompleteProvider as N, isRuntimeBindableKeyId as O, Container as P, dispatchMouseEvent as Q, Input as R, isPhysicalEscapeAction as S, resolveCommandFooterFallback as St, APP_KEYBINDINGS as T, ScrollView as U, MouseRegion as V, SettingsList as W, decodeKittyPrintable as X, VStack as Y, decodePrintableKey as Z, normalizeSkillInvocation as _, wrapTextWithAnsi as _t, API_VERSION as a, getOsc8LinkAtColumn as at, DEFAULT_LEADER_TIMEOUT_MS as b, isFooterLayout as bt, HOST_COMMAND_CATALOG as c, isKeyRelease as ct, classifyCommandLine as d, parseKey as dt, fuzzyFilter as et, commandIsLocalForAttachments as f, registerKittyImageMetadata as ft, localCommandMayWrite as g, visibleWidth as gt, isPlainExitPrompt as h, truncateToWidth as ht, PI_TUI_EXTENSIONS_SERVICE as i, getKeybindings as it, AltScreenSearchIndex as j, isTextProducingKeyId as k, LOCAL_COMMANDS as l, isKeyRepeat as lt, isLocalCommandLine as m, stripTerminalSequences as mt, inject as n, getCellDimensions as nt, describeKey as o, imageFallback as ot, isBareCommandLine as p, sliceByColumn as pt, TuiAltScreen as q, name as r, getGraphemeSegmenter as rt, InvalidateBatcher as s, isFocusable as st, apply as t, getCapabilities as tt, SESSIONLESS_COMMANDS as u, matchesKey as ut, shouldConsumeAdvertisedMiss as v, defaultHideInTsp as vt, parseUserKeybindings as w, isEditorSubmitPreSubmitKey as x, parseFooterLayout as xt, normalizeInputEvent as y, hideFooterRefInTsp as yt, Key as z };