clikcode 1.0.3 → 1.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -12649,30 +12649,295 @@ var init_structured_output = __esm({
12649
12649
  }
12650
12650
  });
12651
12651
 
12652
- // src/tui/inline.ts
12653
- import { spawnSync } from "node:child_process";
12654
- function tmuxForwardsMouse() {
12655
- if (tmuxMouse === void 0) {
12656
- try {
12657
- tmuxMouse = spawnSync("tmux", ["show-options", "-gv", "mouse"], { encoding: "utf8", timeout: 500 }).stdout.trim() === "on";
12658
- } catch {
12659
- tmuxMouse = false;
12652
+ // src/tui/render/hyperlinks.ts
12653
+ function hyperlinksSupported(environment = process.env, isTty = Boolean(process.stdout.isTTY)) {
12654
+ const flag = (value) => value !== void 0 && value !== "" && value !== "0" && value.toLowerCase() !== "false";
12655
+ if (!isTty || (environment.TERM ?? "").toLowerCase() === "dumb") return false;
12656
+ if (flag(environment.CLIKCODE_HYPERLINKS) || flag(environment.FORCE_HYPERLINK)) return true;
12657
+ if (environment.TMUX || environment.STY || /^(?:screen|tmux)/.test(environment.TERM ?? "")) return false;
12658
+ const program3 = (environment.TERM_PROGRAM ?? "").toLowerCase();
12659
+ if (["iterm.app", "wezterm", "vscode", "ghostty", "hyper", "kitty", "rio", "warpterminal", "termius"].includes(program3)) return true;
12660
+ if (environment.KITTY_WINDOW_ID || environment.WT_SESSION || environment.KONSOLE_VERSION || environment.DOMTERM) return true;
12661
+ if (Number(environment.VTE_VERSION ?? 0) >= 5e3) return true;
12662
+ return /^(?:xterm-kitty|xterm-ghostty|foot|alacritty|wezterm|contour)/.test(environment.TERM ?? "");
12663
+ }
12664
+ function closeOpenHyperlink(row) {
12665
+ const last2 = row.lastIndexOf("\x1B]8;");
12666
+ const closedLink = last2 === -1 || row.startsWith(HYPERLINK_CLOSE, last2) ? row : `${row}${HYPERLINK_CLOSE}`;
12667
+ if (!UNDERLINE_ON.test(closedLink)) return closedLink;
12668
+ let underline = false;
12669
+ for (const match of closedLink.matchAll(/\u001b\[([0-9;]*)m/g)) {
12670
+ const params = match[1].split(";").filter(Boolean).map(Number);
12671
+ if (params.length === 0 || params.includes(0)) {
12672
+ underline = false;
12673
+ continue;
12674
+ }
12675
+ if (params.includes(4)) underline = true;
12676
+ if (params.includes(24)) underline = false;
12677
+ }
12678
+ return underline ? `${closedLink}\x1B[24m` : closedLink;
12679
+ }
12680
+ var HYPERLINK_CLOSE, hyperlinkOpen, hyperlinksEnabled, linksOn, UNDERLINE_ON;
12681
+ var init_hyperlinks = __esm({
12682
+ "src/tui/render/hyperlinks.ts"() {
12683
+ "use strict";
12684
+ HYPERLINK_CLOSE = "\x1B]8;;\x1B\\";
12685
+ hyperlinkOpen = (href) => `\x1B]8;;${href}\x1B\\`;
12686
+ linksOn = () => hyperlinksEnabled ?? (hyperlinksEnabled = hyperlinksSupported());
12687
+ UNDERLINE_ON = /\u001b\[(?:[0-9;]*;)?4[;m]/;
12688
+ }
12689
+ });
12690
+
12691
+ // src/tui/render/width.ts
12692
+ function visibleSlice(value, width) {
12693
+ if (terminalCellWidth(value) <= width) return value;
12694
+ const available = Math.max(0, width - 1);
12695
+ let rendered = "";
12696
+ let renderedWidth = 0;
12697
+ let sawAnsi = false;
12698
+ const tokens = displayTokens(value);
12699
+ let linkOpen = false;
12700
+ for (const token of tokens) {
12701
+ if (token[0] === "\x1B") {
12702
+ rendered += token;
12703
+ if (OSC8_SEQUENCE.test(token)) linkOpen = token !== HYPERLINK_CLOSE;
12704
+ else sawAnsi = true;
12705
+ continue;
12660
12706
  }
12707
+ const tokenWidth = terminalCellWidth(token);
12708
+ if (renderedWidth + tokenWidth > available) break;
12709
+ rendered += token;
12710
+ renderedWidth += tokenWidth;
12711
+ }
12712
+ return `${rendered}${linkOpen ? HYPERLINK_CLOSE : ""}${sawAnsi ? "\x1B[0m" : ""}\u2026`;
12713
+ }
12714
+ function visibleTail(value, width) {
12715
+ if (terminalCellWidth(value) <= width) return value;
12716
+ const tokens = displayTokens(value);
12717
+ let kept = "";
12718
+ let keptWidth = 0;
12719
+ for (let index = tokens.length - 1; index >= 0; index -= 1) {
12720
+ const tokenWidth = terminalCellWidth(tokens[index]);
12721
+ if (keptWidth + tokenWidth > Math.max(0, width - 1)) break;
12722
+ kept = tokens[index] + kept;
12723
+ keptWidth += tokenWidth;
12724
+ }
12725
+ return `\u2026${kept}`;
12726
+ }
12727
+ function visiblePathTail(path57, width) {
12728
+ if (terminalCellWidth(path57) <= width) return path57;
12729
+ const parts = path57.split(/(?=[\\/])/);
12730
+ let kept = "";
12731
+ for (let index = parts.length - 1; index >= 0; index -= 1) {
12732
+ if (terminalCellWidth(`\u2026${parts[index]}${kept}`) > width) break;
12733
+ kept = `${parts[index]}${kept}`;
12734
+ }
12735
+ return kept ? `\u2026${kept}` : visibleSlice(`\u2026${parts[parts.length - 1]}`, width);
12736
+ }
12737
+ function isWideCodePoint(code) {
12738
+ if (code < 4352) return false;
12739
+ return code <= 4447 || code === 9001 || code === 9002 || code >= 11904 && code <= 12350 || code >= 12353 && code <= 19903 || code >= 19968 && code <= 42191 || code >= 43360 && code <= 43391 || code >= 44032 && code <= 55203 || code >= 63744 && code <= 64255 || code >= 65040 && code <= 65049 || code >= 65072 && code <= 65135 || code >= 65281 && code <= 65376 || code >= 65504 && code <= 65510 || code >= 127462 && code <= 127487 || code >= 94176 && code <= 94180 || code >= 94208 && code <= 101119 || code >= 110592 && code <= 111359 || code >= 127488 && code <= 127490 || code >= 127504 && code <= 127547 || code >= 127552 && code <= 127560 || code >= 127568 && code <= 127569 || code >= 127584 && code <= 127589 || code >= 127744 && code <= 129791 || code >= 131072 && code <= 262141;
12740
+ }
12741
+ function drawsNothing(code, character) {
12742
+ if (code < 160) return false;
12743
+ if (code === 8232 || code === 8233) return true;
12744
+ return FORMAT.test(character) && !(code >= 1536 && code <= 1541 || code === 1757 || code === 1807 || code === 2192 || code === 2193 || code === 2274);
12745
+ }
12746
+ function displayTokens(value) {
12747
+ const tokens = [];
12748
+ const pushText = (text7) => {
12749
+ for (const { segment } of graphemes().segment(text7)) tokens.push(segment);
12750
+ };
12751
+ let consumed = 0;
12752
+ for (const match of value.matchAll(ZERO_WIDTH_SEQUENCES)) {
12753
+ const start2 = match.index;
12754
+ if (start2 > consumed) pushText(value.slice(consumed, start2));
12755
+ tokens.push(match[0]);
12756
+ consumed = start2 + match[0].length;
12757
+ }
12758
+ if (consumed < value.length) pushText(value.slice(consumed));
12759
+ return tokens;
12760
+ }
12761
+ function oneCell(code) {
12762
+ let known = ONE_CELL[code];
12763
+ if (!known) {
12764
+ const character = String.fromCharCode(code);
12765
+ const joins = code >= 55296 && code <= 57343 || code >= 4352 && code <= 4607 || code >= 43360 && code <= 43391 || code >= 55216 && code <= 55295 || code >= 1536 && code <= 1541 || code === 1757 || code === 1807 || code === 2192 || code === 2193 || code === 2274 || code === 3406 || code === 3635 || code === 3763 || code === 8205;
12766
+ known = joins || isWideCodePoint(code) || MARK.test(character) || GRAPHEME_EXTEND.test(character) || drawsNothing(code, character) || EMOJI_PRESENTATION.test(character) ? 2 : 1;
12767
+ ONE_CELL[code] = known;
12661
12768
  }
12662
- return tmuxMouse;
12769
+ return known === 1;
12663
12770
  }
12664
- function inlineHistoryMode(env3 = process.env, tmuxMouseOn = tmuxForwardsMouse) {
12665
- if (env3.CLIKCODE_INLINE === "1") return true;
12666
- if (env3.CLIKCODE_INLINE === "0") return false;
12667
- const term = (env3.TERM ?? "").toLowerCase();
12668
- if (env3.TMUX) {
12669
- if (!tmuxMouseOn()) return true;
12670
- } else if (env3.STY || term.startsWith("screen") || term.startsWith("tmux")) return true;
12671
- if (term === "dumb" || term === "linux") return true;
12672
- const program3 = (env3.TERM_PROGRAM ?? "").toLowerCase();
12673
- const good = GOOD_TERMINAL_PROGRAMS.has(program3) || GOOD_TERMS.has(term);
12674
- if (good) return false;
12675
- return Boolean(env3.SSH_CONNECTION || env3.SSH_TTY);
12771
+ function simpleWidth(value) {
12772
+ let width = 0;
12773
+ for (let index = 0; index < value.length; index += 1) {
12774
+ const code = value.charCodeAt(index);
12775
+ if (code >= 32 && code < 127) width += 1;
12776
+ else if (code === 27) {
12777
+ const next = value.charCodeAt(index + 1);
12778
+ let end = index + 2;
12779
+ if (next === 91) {
12780
+ while (end < value.length && (value.charCodeAt(end) >= 48 && value.charCodeAt(end) <= 57 || value.charCodeAt(end) === 59)) end += 1;
12781
+ if (value.charCodeAt(end) !== 109) return -1;
12782
+ } else if (next === 93 && value.startsWith("8;", end)) {
12783
+ while (end < value.length && !"\x07\x1B\n".includes(value[end])) end += 1;
12784
+ if (value.charCodeAt(end) !== 27 || value.charCodeAt(end + 1) !== 92) return -1;
12785
+ end += 1;
12786
+ } else return -1;
12787
+ index = end;
12788
+ } else if (code === 9) width += TAB_WIDTH - width % TAB_WIDTH;
12789
+ else if (code < 160) continue;
12790
+ else if (oneCell(code)) width += 1;
12791
+ else return -1;
12792
+ }
12793
+ return width;
12794
+ }
12795
+ function terminalCellWidth(value) {
12796
+ const simple = simpleWidth(value);
12797
+ if (simple >= 0) return simple;
12798
+ const plain3 = value.includes("\x1B") ? value.replace(ZERO_WIDTH_SEQUENCES, "") : value;
12799
+ let width = 0;
12800
+ for (const { segment } of graphemes().segment(plain3)) {
12801
+ if (segment === " ") {
12802
+ width += TAB_WIDTH - width % TAB_WIDTH;
12803
+ continue;
12804
+ }
12805
+ if (CONTROLS.test(segment)) continue;
12806
+ const code = segment.codePointAt(0) ?? 0;
12807
+ if (segment.length === 1 && code < 127) {
12808
+ width += 1;
12809
+ continue;
12810
+ }
12811
+ const base = String.fromCodePoint(code);
12812
+ if (MARK.test(base) || drawsNothing(code, base)) continue;
12813
+ const wide = segment.includes("\uFE0E") ? isWideCodePoint(code) && code >= 126976 : isWideCodePoint(code) || EMOJI_PRESENTATION.test(base) || segment.includes("\uFE0F") && EMOJI.test(base) && !KEYCAP_BASE.test(base) || segment.includes("\u20E3");
12814
+ width += wide ? 2 : 1;
12815
+ }
12816
+ return width;
12817
+ }
12818
+ function previousCharacterIndex(value, index) {
12819
+ if (index <= 0) return 0;
12820
+ const start2 = Math.max(0, index - CLUSTER_WINDOW);
12821
+ let boundary = 0;
12822
+ for (const { index: offset } of graphemes().segment(value.slice(start2, index))) boundary = offset;
12823
+ return start2 + boundary;
12824
+ }
12825
+ function nextCharacterIndex(value, index) {
12826
+ if (index >= value.length) return value.length;
12827
+ const [first2] = graphemes().segment(value.slice(index, index + CLUSTER_WINDOW));
12828
+ return index + (first2 ? first2.segment.length : 1);
12829
+ }
12830
+ var OSC8_SEQUENCE, ZERO_WIDTH_SEQUENCES, TAB_WIDTH, graphemeSegmenter, graphemes, CLUSTER_WINDOW, FORMAT, CONTROLS, MARK, EMOJI_PRESENTATION, EMOJI, KEYCAP_BASE, GRAPHEME_EXTEND, ONE_CELL;
12831
+ var init_width = __esm({
12832
+ "src/tui/render/width.ts"() {
12833
+ "use strict";
12834
+ init_hyperlinks();
12835
+ OSC8_SEQUENCE = /^\u001b\]8;[^\u0007\u001b\n]*\u001b\\$/;
12836
+ ZERO_WIDTH_SEQUENCES = /\u001b\[[0-9;]*m|\u001b\]8;[^\u0007\u001b\n]*\u001b\\/g;
12837
+ TAB_WIDTH = 4;
12838
+ graphemes = () => graphemeSegmenter ??= new Intl.Segmenter(void 0, { granularity: "grapheme" });
12839
+ CLUSTER_WINDOW = 32;
12840
+ FORMAT = new RegExp("\\p{Cf}", "u");
12841
+ CONTROLS = /^[\u0000-\u001f\u007f-\u009f]+$/;
12842
+ MARK = new RegExp("\\p{Mark}", "u");
12843
+ EMOJI_PRESENTATION = new RegExp("\\p{Emoji_Presentation}", "u");
12844
+ EMOJI = new RegExp("\\p{Emoji}", "u");
12845
+ KEYCAP_BASE = /^[0-9#*]$/;
12846
+ GRAPHEME_EXTEND = new RegExp("\\p{Grapheme_Extend}", "u");
12847
+ ONE_CELL = new Uint8Array(65536);
12848
+ }
12849
+ });
12850
+
12851
+ // src/tui/render/text.ts
12852
+ function expandTabs(value, tabWidth = TAB_WIDTH) {
12853
+ if (!value.includes(" ")) return value;
12854
+ return value.split("\n").map((line3) => {
12855
+ if (!line3.includes(" ")) return line3;
12856
+ let column = 0;
12857
+ let expanded = "";
12858
+ for (const [index, part] of line3.split(" ").entries()) {
12859
+ if (index > 0) {
12860
+ const fill2 = tabWidth - column % tabWidth;
12861
+ expanded += " ".repeat(fill2);
12862
+ column += fill2;
12863
+ }
12864
+ expanded += part;
12865
+ column += terminalCellWidth(part);
12866
+ }
12867
+ return expanded;
12868
+ }).join("\n");
12869
+ }
12870
+ function sanitizeTerminalText(value, options2 = {}) {
12871
+ const clean2 = options2.keepSgr ? !UNSAFE_IN_STYLED_TEXT.test(value) : !(options2.keepTabs ? NEEDS_SANITIZING_KEEP_TABS : NEEDS_SANITIZING).test(value);
12872
+ if (clean2 && !(options2.singleLine && value.includes("\n"))) return value;
12873
+ let text7 = value.replace(/\r\n?/g, "\n");
12874
+ text7 = text7.replace(ESCAPE_SEQUENCE, (sequence) => options2.keepSgr && (SGR_SEQUENCE.test(sequence) || OSC8_SEQUENCE.test(sequence)) ? sequence : "");
12875
+ text7 = text7.replace(CONTROL_CHARACTERS, (character) => character === "\x1B" && options2.keepSgr ? character : "");
12876
+ if (!options2.keepTabs) text7 = expandTabs(text7, options2.tabWidth ?? TAB_WIDTH);
12877
+ return options2.singleLine ? text7.replace(/\n/g, " ") : text7;
12878
+ }
12879
+ var ESCAPE_SEQUENCE, SGR_SEQUENCE, SAFE_LINK, NEEDS_SANITIZING, NEEDS_SANITIZING_KEEP_TABS, UNSAFE_IN_STYLED_TEXT, CONTROL_CHARACTERS;
12880
+ var init_text = __esm({
12881
+ "src/tui/render/text.ts"() {
12882
+ "use strict";
12883
+ init_width();
12884
+ ESCAPE_SEQUENCE = new RegExp([
12885
+ "\\u001b\\][^\\u0007\\u001b\\n]*(?:\\u0007|\\u001b\\\\)?",
12886
+ "\\u001b[PX^_][^\\u001b\\n]*(?:\\u001b\\\\)?",
12887
+ "(?:\\u001b\\[|\\u009b)[0-?]*[ -/]*[@-~]?",
12888
+ "\\u001b[ -/]*[0-~]?"
12889
+ ].join("|"), "g");
12890
+ SGR_SEQUENCE = /^\u001b\[[0-9;]*m$/;
12891
+ SAFE_LINK = /^(?:https?:\/\/|mailto:)[^\s\u0000-\u001f\u007f-\u009f]+$/i;
12892
+ NEEDS_SANITIZING = /[\u0000-\u0008\u000b-\u001f\u007f-\u009f\t]/;
12893
+ NEEDS_SANITIZING_KEEP_TABS = /[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/;
12894
+ UNSAFE_IN_STYLED_TEXT = /[\u0000-\u0009\u000b-\u001a\u001c-\u001f\u007f-\u009f]|\u001b(?!\[[0-9;]*m|\]8;[^\u0007\u001b\n]*\u001b\\)/;
12895
+ CONTROL_CHARACTERS = /[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g;
12896
+ }
12897
+ });
12898
+
12899
+ // src/tui/keys.ts
12900
+ function environmentFlag(...values) {
12901
+ return values.some((value) => {
12902
+ const normalized = (value ?? "").trim().toLowerCase();
12903
+ return normalized === "1" || normalized === "true" || normalized === "yes" || normalized === "on";
12904
+ });
12905
+ }
12906
+ function pastedText(key3) {
12907
+ return key3.startsWith(PASTE_START) && key3.endsWith(PASTE_END) ? sanitizeTerminalText(key3.slice(PASTE_START.length, key3.length - PASTE_END.length), { keepTabs: true }) : void 0;
12908
+ }
12909
+ function kittyKeyboardSafe(environment = process.env) {
12910
+ if (environmentFlag(environment.CLIKCODE_NO_KITTY_KEYBOARD)) return false;
12911
+ if (environment.TMUX || environment.STY || /^(?:screen|tmux)/.test(environment.TERM ?? "")) return false;
12912
+ const program3 = (environment.TERM_PROGRAM ?? "").toLowerCase();
12913
+ return Boolean(environment.KITTY_WINDOW_ID || environment.GHOSTTY_RESOURCES_DIR || environment.WEZTERM_PANE || /^(?:xterm-kitty|xterm-ghostty|foot|alacritty|wezterm)/.test(environment.TERM ?? "") || program3 === "wezterm" || program3 === "ghostty" || program3 === "kitty");
12914
+ }
12915
+ var PASTE_START, PASTE_END, PUSH_KITTY_KEYBOARD, POP_KITTY_KEYBOARD, NEWLINE_KEY;
12916
+ var init_keys = __esm({
12917
+ "src/tui/keys.ts"() {
12918
+ "use strict";
12919
+ init_text();
12920
+ PASTE_START = "\x1B[200~";
12921
+ PASTE_END = "\x1B[201~";
12922
+ PUSH_KITTY_KEYBOARD = "\x1B[>1u";
12923
+ POP_KITTY_KEYBOARD = "\x1B[<u";
12924
+ NEWLINE_KEY = "\x1B\r";
12925
+ }
12926
+ });
12927
+
12928
+ // src/tui/inline.ts
12929
+ function inlineHistoryMode(env3 = process.env) {
12930
+ if (env3.CLIKDEPLOY_CLIENT === "mobile") return false;
12931
+ return env3.CLIKCODE_INLINE === "1";
12932
+ }
12933
+ function swallowsAlternateScreen(env3 = process.env) {
12934
+ return Boolean(env3.STY) && !env3.TMUX;
12935
+ }
12936
+ function restoreMainBlock() {
12937
+ const main = inlineBlock.main;
12938
+ inlineBlock.main = void 0;
12939
+ inlineBlock.page = false;
12940
+ if (main) Object.assign(inlineBlock, main, { found: void 0, lost: false });
12676
12941
  }
12677
12942
  function eraseInlineBlock() {
12678
12943
  const out2 = inlineBlock.rows ? `${inlineBlock.cursorRow > 0 ? `\x1B[${inlineBlock.cursorRow}A` : ""}\r\x1B[J` : "";
@@ -12681,16 +12946,12 @@ function eraseInlineBlock() {
12681
12946
  inlineBlock.last = "";
12682
12947
  inlineBlock.liveRows = [];
12683
12948
  inlineBlock.pad = 0;
12684
- inlineBlock.padOverSaved = false;
12685
- inlineBlock.slack = 0;
12686
12949
  return out2;
12687
12950
  }
12688
- var GOOD_TERMINAL_PROGRAMS, GOOD_TERMS, tmuxMouse, CLEAR_SCREEN_AND_SCROLLBACK, CLEAR_SCREEN, inlineBlock;
12951
+ var CLEAR_SCREEN_AND_SCROLLBACK, CLEAR_SCREEN, inlineBlock, ENTER_PAGE_SCREEN, LEAVE_PAGE_SCREEN;
12689
12952
  var init_inline = __esm({
12690
12953
  "src/tui/inline.ts"() {
12691
12954
  "use strict";
12692
- GOOD_TERMINAL_PROGRAMS = /* @__PURE__ */ new Set(["iterm.app", "apple_terminal", "wezterm", "ghostty", "kitty", "vscode", "alacritty"]);
12693
- GOOD_TERMS = /* @__PURE__ */ new Set(["xterm-kitty", "alacritty", "xterm-ghostty", "wezterm"]);
12694
12955
  CLEAR_SCREEN_AND_SCROLLBACK = "\x1B[2J\x1B[3J\x1B[H";
12695
12956
  CLEAR_SCREEN = "\x1B[H\x1B[K\x1B[2;1H\x1B[J\x1B[H";
12696
12957
  inlineBlock = {
@@ -12700,30 +12961,35 @@ var init_inline = __esm({
12700
12961
  last: "",
12701
12962
  liveRows: [],
12702
12963
  columns: 0,
12703
- /** The blank rows above the conversation (a conversation shorter than the screen) that retired rows have not yet used. */
12964
+ /** The blank rows above the conversation (a conversation shorter than the screen, drawn on the last rows at the start) that
12965
+ * retired rows have not yet used. Only true while the block ends on the last row: a resize or a shrinking block zeroes it. */
12704
12966
  pad: 0,
12705
- /** The blank rows above the conversation stand over saved lines that hold part of it (a terminal that did not pull them
12706
- * back when its screen grew, and the block was pushed down instead): a shrink pushes them into the saved lines, which
12707
- * are not the blank rows of a short conversation and must never be cleared as if they were. */
12708
- padOverSaved: false,
12709
- /** The blank rows below the block that a terminal added when its screen grew and that nothing could take: the block is
12710
- * that many rows above the last, until output fills them. */
12711
- slack: 0,
12712
- /** The screen height the block was last placed for: it ended on the last row of a screen this tall. */
12967
+ /** The screen row the block's first row is on: measured after a change of height, otherwise followed from where it was drawn. */
12968
+ top: 0,
12969
+ /** The screen height the block was last drawn for. */
12713
12970
  height: 0,
12714
- /** After a settled change of height, the screen row the terminal's cursor report puts the block's first row on (undefined
12715
- * when nothing was asked); the next frame consumes it. `measuring` holds frames back while the question is out. */
12971
+ /** After a settled change of height, the screen row the block's first row is on, from the terminal's cursor report
12972
+ * (negative: its top rows went into the saved lines); undefined when nothing was asked. The next frame consumes it.
12973
+ * `measuring` holds frames back while the question is out. */
12716
12974
  found: void 0,
12717
12975
  measuring: false,
12718
- /** The cursor report never came back after a change of height: where the block stands is unknown, so the next frame
12719
- * erases and draws it from the cursor, with no vertical re-anchoring guessed (see anchorBlock). */
12976
+ /** The cursor report never came back after a change of height: the block is erased and drawn again relative to where
12977
+ * it was last left (see anchorBlock). */
12720
12978
  lost: false,
12721
- /** A modal surface (the board, the palette, a picker) is on screen: it is the whole visible screen, drawn from its top
12722
- * row, and the conversation is not (see flushInlineFrame). `tail` is what the conversation had on the visible rows when
12723
- * the surface opened, plus every row it retired since: they are written again, ahead of the block, when it closes. */
12979
+ /** A modal surface (the board, the palette, a picker) is on screen: it is drawn on the ALTERNATE screen (`?1049h`), from its
12980
+ * top row, so no saved lines exist behind it in any client and the main screen (the conversation and its live block) is not
12981
+ * touched; closing it (`?1049l`) shows that screen again as it was. `main` is the block's state on the main screen, kept while
12982
+ * the page is up and put back when it closes. `tail` is every row the conversation retired meanwhile: written above the block
12983
+ * once the page is gone. `resized`: the size changed while it was up, so the main screen is measured again on close.
12984
+ * `wipe`: the conversation was rewritten (a new width) while it was up, so the main screen is cleared and it is written whole. */
12724
12985
  page: false,
12725
- tail: []
12986
+ tail: [],
12987
+ resized: false,
12988
+ wipe: false,
12989
+ main: void 0
12726
12990
  };
12991
+ ENTER_PAGE_SCREEN = `\x1B[?1049h${CLEAR_SCREEN}`;
12992
+ LEAVE_PAGE_SCREEN = "\x1B[?1049l";
12727
12993
  }
12728
12994
  });
12729
12995
 
@@ -12765,11 +13031,47 @@ var init_terminal_signals = __esm({
12765
13031
  // src/tui/restore.ts
12766
13032
  import { writeSync } from "node:fs";
12767
13033
  import { stdin as input, stdout as output } from "node:process";
13034
+ function reexecHandover(env3 = process.env) {
13035
+ return inlineHistoryMode(env3) ? "inline" : "alt";
13036
+ }
13037
+ function parseReexecHandover(value) {
13038
+ return value === "inline" || value === "alt" || value === "1" ? value : void 0;
13039
+ }
13040
+ function reconcileScreen(handover, inline2, rows) {
13041
+ const inlineStart = `${CLEAR_SCREEN_AND_SCROLLBACK}\x1B[${Math.max(1, rows)};1H`;
13042
+ if (inline2) return { write: `${handover === "alt" || handover === "1" ? "\x1B[?1049l" : ""}${inlineStart}`, inherited: handover !== void 0 };
13043
+ if (handover === void 0) return { write: enterAlternateScreenSequence(), inherited: false };
13044
+ if (handover === "alt") return { write: "", inherited: true };
13045
+ return { write: `${CLEAR_SCREEN_AND_SCROLLBACK}${enterAlternateScreenSequence()}`, inherited: true };
13046
+ }
13047
+ function enterAlternateScreenSequence() {
13048
+ if (!swallowsAlternateScreen()) return "\x1B[?1049h\x1B[2J\x1B[H";
13049
+ return `\x1B[?1049h${"\r\n".repeat(Math.max(1, output.rows || 24))}${CLEAR_SCREEN}`;
13050
+ }
13051
+ function historyDumpSequence() {
13052
+ if (historyDump.suppressed || !historyDump.source || inlineHistoryMode()) return "";
13053
+ let text7 = "";
13054
+ try {
13055
+ text7 = historyDump.source();
13056
+ } catch {
13057
+ }
13058
+ const wipe = swallowsAlternateScreen() ? `${CLEAR_SCREEN}` : "";
13059
+ return text7 || wipe ? `${wipe}${text7}` : "";
13060
+ }
12768
13061
  function enterAlternateScreen() {
12769
13062
  if (terminalModes.alternateScreen || inlineHistoryMode()) return;
12770
- output.write(ENTER_ALTERNATE_SCREEN);
13063
+ output.write(enterAlternateScreenSequence());
12771
13064
  terminalModes.alternateScreen = true;
12772
13065
  }
13066
+ function leavePage() {
13067
+ if (!inlineBlock.page) return "";
13068
+ restoreMainBlock();
13069
+ inlineBlock.tail = [];
13070
+ inlineBlock.resized = false;
13071
+ inlineBlock.wipe = false;
13072
+ terminalModes.alternateScreen = false;
13073
+ return LEAVE_PAGE_SCREEN;
13074
+ }
12773
13075
  function pushShellTitle() {
12774
13076
  if (!output.isTTY || terminalModes.titlePushed) return false;
12775
13077
  output.write(PUSH_TITLE);
@@ -12777,7 +13079,7 @@ function pushShellTitle() {
12777
13079
  return true;
12778
13080
  }
12779
13081
  function giveBackTerminal(readModesOff) {
12780
- output.write(`${readModesOff}` + terminalTeardown(terminalModes.alternateScreen) + signalsTeardown());
13082
+ output.write(`${readModesOff}` + terminalTeardown(terminalModes.alternateScreen) + signalsTeardown() + historyDumpSequence());
12781
13083
  terminalModes.alternateScreen = false;
12782
13084
  terminalModes.painted = false;
12783
13085
  }
@@ -12788,14 +13090,18 @@ function signalsTeardown() {
12788
13090
  return sequence;
12789
13091
  }
12790
13092
  function terminalPrepare() {
12791
- return `${MOUSE_MODES_OFF}${READ_MODES_OFF}${LATCHED_OFF}`;
13093
+ const kitty = kittyKeyboardSafe() ? CLEAR_KITTY_KEYBOARD : "";
13094
+ return `${kitty}${MOUSE_MODES_OFF}${READ_MODES_OFF}${LATCHED_OFF}`;
12792
13095
  }
12793
13096
  function terminalTeardown(leavingAlternateScreen) {
12794
- return `${MOUSE_MODES_OFF}${READ_MODES_OFF}${leavingAlternateScreen ? "\x1B[?1049l" : ""}${MOUSE_MODES_OFF}${READ_MODES_OFF}${LATCHED_OFF}\x1B[?7h\x1B[?25h`;
13097
+ const scroll = terminalModes.alternateScroll ? "\x1B[?1007l" : "";
13098
+ terminalModes.alternateScroll = false;
13099
+ const modesOff = `${MOUSE_MODES_OFF}${READ_MODES_OFF}${scroll}`;
13100
+ return `${leavingAlternateScreen ? `${modesOff}\x1B[?1049l` : ""}${modesOff}${LATCHED_OFF}\x1B[?7h\x1B[?25h`;
12795
13101
  }
12796
13102
  function restoreTerminal(options2 = {}) {
12797
13103
  try {
12798
- const touched = terminalModes.uiStarted || terminalModes.painted || terminalModes.kittyKeyboard || terminalModes.bracketedPaste || terminalModes.wheelReporting || terminalModes.alternateScreen || terminalModes.rawMode || terminalModes.titlePushed || terminalModes.progress;
13104
+ const touched = terminalModes.uiStarted || terminalModes.painted || terminalModes.kittyKeyboard || terminalModes.bracketedPaste || terminalModes.wheelReporting || terminalModes.alternateScroll || terminalModes.alternateScreen || terminalModes.rawMode || terminalModes.titlePushed || terminalModes.progress;
12799
13105
  if (!touched) {
12800
13106
  if (input.isRaw && input.isTTY && typeof input.setRawMode === "function") input.setRawMode(false);
12801
13107
  return;
@@ -12803,8 +13109,10 @@ function restoreTerminal(options2 = {}) {
12803
13109
  let sequence = "";
12804
13110
  if (terminalModes.painted) sequence += "\x1B[?2026l";
12805
13111
  if (terminalModes.kittyKeyboard) sequence += "\x1B[<u";
12806
- sequence += terminalTeardown(terminalModes.alternateScreen);
13112
+ const leavingAlternate = terminalModes.alternateScreen;
13113
+ sequence += terminalTeardown(leavingAlternate);
12807
13114
  sequence += signalsTeardown();
13115
+ if (leavingAlternate) sequence += historyDumpSequence();
12808
13116
  const wasRaw = terminalModes.rawMode;
12809
13117
  terminalModes.uiStarted = false;
12810
13118
  terminalModes.painted = false;
@@ -12837,18 +13145,20 @@ function installTerminalRestoreSignals() {
12837
13145
  });
12838
13146
  }
12839
13147
  }
12840
- var REEXEC_TERMINAL_ENV, ENTER_ALTERNATE_SCREEN, terminalModes, MOUSE_MODES_OFF, READ_MODES_OFF, LATCHED_OFF, RESTORE_SIGNALS, restoreSignalsInstalled;
13148
+ var REEXEC_TERMINAL_ENV, historyDump, terminalModes, CLEAR_KITTY_KEYBOARD, MOUSE_MODES_OFF, READ_MODES_OFF, LATCHED_OFF, RESTORE_SIGNALS, restoreSignalsInstalled;
12841
13149
  var init_restore = __esm({
12842
13150
  "src/tui/restore.ts"() {
12843
13151
  "use strict";
13152
+ init_keys();
12844
13153
  init_inline();
12845
13154
  init_terminal_signals();
12846
13155
  REEXEC_TERMINAL_ENV = "CLIKCODE_KEEP_TERMINAL_ON_REEXEC";
12847
- ENTER_ALTERNATE_SCREEN = "\x1B[?1049h\x1B[2J\x1B[H";
13156
+ historyDump = { source: void 0, suppressed: false };
12848
13157
  terminalModes = {
12849
13158
  bracketedPaste: false,
12850
13159
  kittyKeyboard: false,
12851
13160
  wheelReporting: false,
13161
+ alternateScroll: false,
12852
13162
  alternateScreen: false,
12853
13163
  rawMode: false,
12854
13164
  painted: false,
@@ -12856,6 +13166,7 @@ var init_restore = __esm({
12856
13166
  titlePushed: false,
12857
13167
  progress: false
12858
13168
  };
13169
+ CLEAR_KITTY_KEYBOARD = "\x1B[<99u";
12859
13170
  MOUSE_MODES_OFF = "\x1B[?1006l\x1B[?1016l\x1B[?1003l\x1B[?1002l\x1B[?1000l";
12860
13171
  READ_MODES_OFF = `\x1B[?2004l\x1B[?2031l${FOCUS_REPORTING_OFF}`;
12861
13172
  LATCHED_OFF = "\x1B[>4m\x1B(B\x1B7\x1B[r\x1B8";
@@ -12869,9 +13180,9 @@ var CLIKCODE_VERSION, CLIKCODE_USER_AGENT, CLIKCODE_COMMIT;
12869
13180
  var init_version = __esm({
12870
13181
  "src/version.ts"() {
12871
13182
  "use strict";
12872
- CLIKCODE_VERSION = "1.0.3" ? "1.0.3" : CLIKCODE_VERSION_FALLBACK;
13183
+ CLIKCODE_VERSION = "1.0.4" ? "1.0.4" : CLIKCODE_VERSION_FALLBACK;
12873
13184
  CLIKCODE_USER_AGENT = `ClikCode/${CLIKCODE_VERSION}`;
12874
- CLIKCODE_COMMIT = "b948fac0a909f3dd8b404c888255cc93f3631de2" ? "b948fac0a909f3dd8b404c888255cc93f3631de2" : void 0;
13185
+ CLIKCODE_COMMIT = "974aeaf4f794ca21868f8db062af7dcd93a0db9a" ? "974aeaf4f794ca21868f8db062af7dcd93a0db9a" : void 0;
12875
13186
  }
12876
13187
  });
12877
13188
 
@@ -15292,7 +15603,7 @@ var require_cross_spawn = __commonJS({
15292
15603
  enoent.hookChildProcess(spawned, parsed2);
15293
15604
  return spawned;
15294
15605
  }
15295
- function spawnSync4(command, args, options2) {
15606
+ function spawnSync3(command, args, options2) {
15296
15607
  const parsed2 = parse3(command, args, options2);
15297
15608
  const result = cp3.spawnSync(parsed2.command, parsed2.args, parsed2.options);
15298
15609
  result.error = result.error || enoent.verifyENOENTSync(result.status, parsed2);
@@ -15300,7 +15611,7 @@ var require_cross_spawn = __commonJS({
15300
15611
  }
15301
15612
  module.exports = spawn18;
15302
15613
  module.exports.spawn = spawn18;
15303
- module.exports.sync = spawnSync4;
15614
+ module.exports.sync = spawnSync3;
15304
15615
  module.exports._parse = parse3;
15305
15616
  module.exports._enoent = enoent;
15306
15617
  }
@@ -16895,199 +17206,6 @@ var init_resources = __esm({
16895
17206
  }
16896
17207
  });
16897
17208
 
16898
- // src/tui/render/hyperlinks.ts
16899
- function hyperlinksSupported(environment = process.env, isTty = Boolean(process.stdout.isTTY)) {
16900
- const flag = (value) => value !== void 0 && value !== "" && value !== "0" && value.toLowerCase() !== "false";
16901
- if (!isTty || (environment.TERM ?? "").toLowerCase() === "dumb") return false;
16902
- if (flag(environment.CLIKCODE_HYPERLINKS) || flag(environment.FORCE_HYPERLINK)) return true;
16903
- if (environment.TMUX || environment.STY || /^(?:screen|tmux)/.test(environment.TERM ?? "")) return false;
16904
- const program3 = (environment.TERM_PROGRAM ?? "").toLowerCase();
16905
- if (["iterm.app", "wezterm", "vscode", "ghostty", "hyper", "kitty", "rio", "warpterminal", "termius"].includes(program3)) return true;
16906
- if (environment.KITTY_WINDOW_ID || environment.WT_SESSION || environment.KONSOLE_VERSION || environment.DOMTERM) return true;
16907
- if (Number(environment.VTE_VERSION ?? 0) >= 5e3) return true;
16908
- return /^(?:xterm-kitty|xterm-ghostty|foot|alacritty|wezterm|contour)/.test(environment.TERM ?? "");
16909
- }
16910
- function closeOpenHyperlink(row) {
16911
- const last2 = row.lastIndexOf("\x1B]8;");
16912
- const closedLink = last2 === -1 || row.startsWith(HYPERLINK_CLOSE, last2) ? row : `${row}${HYPERLINK_CLOSE}`;
16913
- if (!UNDERLINE_ON.test(closedLink)) return closedLink;
16914
- let underline = false;
16915
- for (const match of closedLink.matchAll(/\u001b\[([0-9;]*)m/g)) {
16916
- const params = match[1].split(";").filter(Boolean).map(Number);
16917
- if (params.length === 0 || params.includes(0)) {
16918
- underline = false;
16919
- continue;
16920
- }
16921
- if (params.includes(4)) underline = true;
16922
- if (params.includes(24)) underline = false;
16923
- }
16924
- return underline ? `${closedLink}\x1B[24m` : closedLink;
16925
- }
16926
- var HYPERLINK_CLOSE, hyperlinkOpen, hyperlinksEnabled, linksOn, UNDERLINE_ON;
16927
- var init_hyperlinks = __esm({
16928
- "src/tui/render/hyperlinks.ts"() {
16929
- "use strict";
16930
- HYPERLINK_CLOSE = "\x1B]8;;\x1B\\";
16931
- hyperlinkOpen = (href) => `\x1B]8;;${href}\x1B\\`;
16932
- linksOn = () => hyperlinksEnabled ?? (hyperlinksEnabled = hyperlinksSupported());
16933
- UNDERLINE_ON = /\u001b\[(?:[0-9;]*;)?4[;m]/;
16934
- }
16935
- });
16936
-
16937
- // src/tui/render/width.ts
16938
- function visibleSlice(value, width) {
16939
- if (terminalCellWidth(value) <= width) return value;
16940
- const available = Math.max(0, width - 1);
16941
- let rendered = "";
16942
- let renderedWidth = 0;
16943
- let sawAnsi = false;
16944
- const tokens = displayTokens(value);
16945
- let linkOpen = false;
16946
- for (const token of tokens) {
16947
- if (token[0] === "\x1B") {
16948
- rendered += token;
16949
- if (OSC8_SEQUENCE.test(token)) linkOpen = token !== HYPERLINK_CLOSE;
16950
- else sawAnsi = true;
16951
- continue;
16952
- }
16953
- const tokenWidth = terminalCellWidth(token);
16954
- if (renderedWidth + tokenWidth > available) break;
16955
- rendered += token;
16956
- renderedWidth += tokenWidth;
16957
- }
16958
- return `${rendered}${linkOpen ? HYPERLINK_CLOSE : ""}${sawAnsi ? "\x1B[0m" : ""}\u2026`;
16959
- }
16960
- function visibleTail(value, width) {
16961
- if (terminalCellWidth(value) <= width) return value;
16962
- const tokens = displayTokens(value);
16963
- let kept = "";
16964
- let keptWidth = 0;
16965
- for (let index = tokens.length - 1; index >= 0; index -= 1) {
16966
- const tokenWidth = terminalCellWidth(tokens[index]);
16967
- if (keptWidth + tokenWidth > Math.max(0, width - 1)) break;
16968
- kept = tokens[index] + kept;
16969
- keptWidth += tokenWidth;
16970
- }
16971
- return `\u2026${kept}`;
16972
- }
16973
- function visiblePathTail(path57, width) {
16974
- if (terminalCellWidth(path57) <= width) return path57;
16975
- const parts = path57.split(/(?=[\\/])/);
16976
- let kept = "";
16977
- for (let index = parts.length - 1; index >= 0; index -= 1) {
16978
- if (terminalCellWidth(`\u2026${parts[index]}${kept}`) > width) break;
16979
- kept = `${parts[index]}${kept}`;
16980
- }
16981
- return kept ? `\u2026${kept}` : visibleSlice(`\u2026${parts[parts.length - 1]}`, width);
16982
- }
16983
- function isWideCodePoint(code) {
16984
- if (code < 4352) return false;
16985
- return code <= 4447 || code === 9001 || code === 9002 || code >= 11904 && code <= 42191 || code >= 44032 && code <= 55203 || code >= 63744 && code <= 64255 || code >= 65072 && code <= 65135 || code >= 65281 && code <= 65376 || code >= 65504 && code <= 65510 || code >= 127462 && code <= 127487 || code >= 127744 && code <= 129791 || code >= 131072 && code <= 262141;
16986
- }
16987
- function displayTokens(value) {
16988
- const tokens = [];
16989
- const pushText = (text7) => {
16990
- for (const { segment } of graphemes().segment(text7)) tokens.push(segment);
16991
- };
16992
- let consumed = 0;
16993
- for (const match of value.matchAll(ZERO_WIDTH_SEQUENCES)) {
16994
- const start2 = match.index;
16995
- if (start2 > consumed) pushText(value.slice(consumed, start2));
16996
- tokens.push(match[0]);
16997
- consumed = start2 + match[0].length;
16998
- }
16999
- if (consumed < value.length) pushText(value.slice(consumed));
17000
- return tokens;
17001
- }
17002
- function oneCell(code) {
17003
- let known = ONE_CELL[code];
17004
- if (!known) {
17005
- const character = String.fromCharCode(code);
17006
- const joins = code >= 55296 && code <= 57343 || code >= 4352 && code <= 4607 || code >= 43360 && code <= 43391 || code >= 55216 && code <= 55295 || code >= 1536 && code <= 1541 || code === 1757 || code === 1807 || code === 2192 || code === 2193 || code === 2274 || code === 3406 || code === 3635 || code === 3763 || code === 8205;
17007
- known = joins || isWideCodePoint(code) || MARK.test(character) || GRAPHEME_EXTEND.test(character) || EMOJI_PRESENTATION.test(character) ? 2 : 1;
17008
- ONE_CELL[code] = known;
17009
- }
17010
- return known === 1;
17011
- }
17012
- function simpleWidth(value) {
17013
- let width = 0;
17014
- for (let index = 0; index < value.length; index += 1) {
17015
- const code = value.charCodeAt(index);
17016
- if (code >= 32 && code < 127) width += 1;
17017
- else if (code === 27) {
17018
- const next = value.charCodeAt(index + 1);
17019
- let end = index + 2;
17020
- if (next === 91) {
17021
- while (end < value.length && (value.charCodeAt(end) >= 48 && value.charCodeAt(end) <= 57 || value.charCodeAt(end) === 59)) end += 1;
17022
- if (value.charCodeAt(end) !== 109) return -1;
17023
- } else if (next === 93 && value.startsWith("8;", end)) {
17024
- while (end < value.length && !"\x07\x1B\n".includes(value[end])) end += 1;
17025
- if (value.charCodeAt(end) !== 27 || value.charCodeAt(end + 1) !== 92) return -1;
17026
- end += 1;
17027
- } else return -1;
17028
- index = end;
17029
- } else if (code === 9) width += TAB_WIDTH - width % TAB_WIDTH;
17030
- else if (code < 160) continue;
17031
- else if (oneCell(code)) width += 1;
17032
- else return -1;
17033
- }
17034
- return width;
17035
- }
17036
- function terminalCellWidth(value) {
17037
- const simple = simpleWidth(value);
17038
- if (simple >= 0) return simple;
17039
- const plain3 = value.includes("\x1B") ? value.replace(ZERO_WIDTH_SEQUENCES, "") : value;
17040
- let width = 0;
17041
- for (const { segment } of graphemes().segment(plain3)) {
17042
- if (segment === " ") {
17043
- width += TAB_WIDTH - width % TAB_WIDTH;
17044
- continue;
17045
- }
17046
- if (CONTROLS.test(segment)) continue;
17047
- const code = segment.codePointAt(0) ?? 0;
17048
- if (segment.length === 1 && code < 127) {
17049
- width += 1;
17050
- continue;
17051
- }
17052
- const base = String.fromCodePoint(code);
17053
- if (MARK.test(base)) continue;
17054
- const wide = segment.includes("\uFE0E") ? isWideCodePoint(code) && code >= 126976 : isWideCodePoint(code) || EMOJI_PRESENTATION.test(base) || segment.includes("\uFE0F") && EMOJI.test(base) && !KEYCAP_BASE.test(base) || segment.includes("\u20E3");
17055
- width += wide ? 2 : 1;
17056
- }
17057
- return width;
17058
- }
17059
- function previousCharacterIndex(value, index) {
17060
- if (index <= 0) return 0;
17061
- const start2 = Math.max(0, index - CLUSTER_WINDOW);
17062
- let boundary = 0;
17063
- for (const { index: offset } of graphemes().segment(value.slice(start2, index))) boundary = offset;
17064
- return start2 + boundary;
17065
- }
17066
- function nextCharacterIndex(value, index) {
17067
- if (index >= value.length) return value.length;
17068
- const [first2] = graphemes().segment(value.slice(index, index + CLUSTER_WINDOW));
17069
- return index + (first2 ? first2.segment.length : 1);
17070
- }
17071
- var OSC8_SEQUENCE, ZERO_WIDTH_SEQUENCES, TAB_WIDTH, graphemeSegmenter, graphemes, CLUSTER_WINDOW, CONTROLS, MARK, EMOJI_PRESENTATION, EMOJI, KEYCAP_BASE, GRAPHEME_EXTEND, ONE_CELL;
17072
- var init_width = __esm({
17073
- "src/tui/render/width.ts"() {
17074
- "use strict";
17075
- init_hyperlinks();
17076
- OSC8_SEQUENCE = /^\u001b\]8;[^\u0007\u001b\n]*\u001b\\$/;
17077
- ZERO_WIDTH_SEQUENCES = /\u001b\[[0-9;]*m|\u001b\]8;[^\u0007\u001b\n]*\u001b\\/g;
17078
- TAB_WIDTH = 4;
17079
- graphemes = () => graphemeSegmenter ??= new Intl.Segmenter(void 0, { granularity: "grapheme" });
17080
- CLUSTER_WINDOW = 32;
17081
- CONTROLS = /^[\u0000-\u001f\u007f-\u009f]+$/;
17082
- MARK = new RegExp("\\p{Mark}", "u");
17083
- EMOJI_PRESENTATION = new RegExp("\\p{Emoji_Presentation}", "u");
17084
- EMOJI = new RegExp("\\p{Emoji}", "u");
17085
- KEYCAP_BASE = /^[0-9#*]$/;
17086
- GRAPHEME_EXTEND = new RegExp("\\p{Grapheme_Extend}", "u");
17087
- ONE_CELL = new Uint8Array(65536);
17088
- }
17089
- });
17090
-
17091
17209
  // src/harness/protocol/tools.ts
17092
17210
  function formatToolRow(name, detail, category) {
17093
17211
  const lines4 = detail?.trim().split(/\r?\n/) ?? [];
@@ -18868,15 +18986,15 @@ var init_activity_view = __esm({
18868
18986
 
18869
18987
  // src/tui/capabilities.ts
18870
18988
  import { stdin as input3, stdout as output4 } from "node:process";
18871
- function environmentFlag(...values) {
18989
+ function environmentFlag2(...values) {
18872
18990
  const value = values.find((candidate) => candidate !== void 0 && candidate !== "");
18873
18991
  return value !== void 0 && value !== "0" && value.toLowerCase() !== "false";
18874
18992
  }
18875
18993
  function screenReaderMode(environment = process.env) {
18876
- return environmentFlag(environment.CLIKCODE_SCREEN_READER);
18994
+ return environmentFlag2(environment.CLIKCODE_SCREEN_READER);
18877
18995
  }
18878
18996
  function reducedMotion(environment = process.env) {
18879
- return environmentFlag(environment.CLIKCODE_REDUCED_MOTION, environment.NO_MOTION);
18997
+ return environmentFlag2(environment.CLIKCODE_REDUCED_MOTION, environment.NO_MOTION);
18880
18998
  }
18881
18999
  function terminalUiSupported(stdinTty = Boolean(input3.isTTY), stdoutTty = Boolean(output4.isTTY), environment = process.env) {
18882
19000
  if (environment.CLIKCODE_TUI?.trim().toLowerCase() === "classic") return false;
@@ -25708,53 +25826,6 @@ var init_memoize = __esm({
25708
25826
  }
25709
25827
  });
25710
25828
 
25711
- // src/tui/render/text.ts
25712
- function expandTabs(value, tabWidth = TAB_WIDTH) {
25713
- if (!value.includes(" ")) return value;
25714
- return value.split("\n").map((line3) => {
25715
- if (!line3.includes(" ")) return line3;
25716
- let column = 0;
25717
- let expanded = "";
25718
- for (const [index, part] of line3.split(" ").entries()) {
25719
- if (index > 0) {
25720
- const fill2 = tabWidth - column % tabWidth;
25721
- expanded += " ".repeat(fill2);
25722
- column += fill2;
25723
- }
25724
- expanded += part;
25725
- column += terminalCellWidth(part);
25726
- }
25727
- return expanded;
25728
- }).join("\n");
25729
- }
25730
- function sanitizeTerminalText(value, options2 = {}) {
25731
- const clean2 = options2.keepSgr ? !UNSAFE_IN_STYLED_TEXT.test(value) : !NEEDS_SANITIZING.test(value);
25732
- if (clean2 && !(options2.singleLine && value.includes("\n"))) return value;
25733
- let text7 = value.replace(/\r\n?/g, "\n");
25734
- text7 = text7.replace(ESCAPE_SEQUENCE, (sequence) => options2.keepSgr && (SGR_SEQUENCE.test(sequence) || OSC8_SEQUENCE.test(sequence)) ? sequence : "");
25735
- text7 = text7.replace(CONTROL_CHARACTERS, (character) => character === "\x1B" && options2.keepSgr ? character : "");
25736
- text7 = expandTabs(text7, options2.tabWidth ?? TAB_WIDTH);
25737
- return options2.singleLine ? text7.replace(/\n/g, " ") : text7;
25738
- }
25739
- var ESCAPE_SEQUENCE, SGR_SEQUENCE, SAFE_LINK, NEEDS_SANITIZING, UNSAFE_IN_STYLED_TEXT, CONTROL_CHARACTERS;
25740
- var init_text = __esm({
25741
- "src/tui/render/text.ts"() {
25742
- "use strict";
25743
- init_width();
25744
- ESCAPE_SEQUENCE = new RegExp([
25745
- "\\u001b\\][^\\u0007\\u001b\\n]*(?:\\u0007|\\u001b\\\\)?",
25746
- "\\u001b[PX^_][^\\u001b\\n]*(?:\\u001b\\\\)?",
25747
- "(?:\\u001b\\[|\\u009b)[0-?]*[ -/]*[@-~]?",
25748
- "\\u001b[ -/]*[0-~]?"
25749
- ].join("|"), "g");
25750
- SGR_SEQUENCE = /^\u001b\[[0-9;]*m$/;
25751
- SAFE_LINK = /^(?:https?:\/\/|mailto:)[^\s\u0000-\u001f\u007f-\u009f]+$/i;
25752
- NEEDS_SANITIZING = /[\u0000-\u0008\u000b-\u001f\u007f-\u009f\t]/;
25753
- UNSAFE_IN_STYLED_TEXT = /[\u0000-\u0009\u000b-\u001a\u001c-\u001f\u007f-\u009f]|\u001b(?!\[[0-9;]*m|\]8;[^\u0007\u001b\n]*\u001b\\)/;
25754
- CONTROL_CHARACTERS = /[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g;
25755
- }
25756
- });
25757
-
25758
25829
  // src/tui/render/wrap.ts
25759
25830
  function wrapCodeLine(value, width) {
25760
25831
  const safeWidth = Math.max(1, width);
@@ -26329,9 +26400,9 @@ function enqueueSessionTurn(session2, submission, now) {
26329
26400
  session2.updatedAt = now;
26330
26401
  }
26331
26402
  function consumeSessionTurn(session2, id) {
26332
- const queued = session2.queuedTurns ?? [];
26333
- const next = queued.filter((item) => item.id !== id);
26334
- if (next.length === queued.length) return false;
26403
+ const queued2 = session2.queuedTurns ?? [];
26404
+ const next = queued2.filter((item) => item.id !== id);
26405
+ if (next.length === queued2.length) return false;
26335
26406
  if (next.length) session2.queuedTurns = next;
26336
26407
  else delete session2.queuedTurns;
26337
26408
  return true;
@@ -28907,20 +28978,20 @@ async function claudeSessionTitle(path57) {
28907
28978
  for (const line3 of prefix.split("\n")) {
28908
28979
  if (!line3.trim()) continue;
28909
28980
  let text7;
28910
- let queued = false;
28981
+ let queued2 = false;
28911
28982
  try {
28912
28983
  const record6 = JSON.parse(line3);
28913
- queued = record6.type === "queue-operation" && record6.operation === "enqueue";
28914
- if (record6.type !== "user" && !queued) continue;
28915
- text7 = visibleNativeUserText(queued ? typeof record6.content === "string" ? record6.content : "" : extractMessageText(record6.message?.content));
28984
+ queued2 = record6.type === "queue-operation" && record6.operation === "enqueue";
28985
+ if (record6.type !== "user" && !queued2) continue;
28986
+ text7 = visibleNativeUserText(queued2 ? typeof record6.content === "string" ? record6.content : "" : extractMessageText(record6.message?.content));
28916
28987
  } catch {
28917
- queued = /"type"\s*:\s*"queue-operation"/.test(line3) && line3.includes('"enqueue"');
28918
- if (!queued && !/"type"\s*:\s*"user"|"role"\s*:\s*"user"/.test(line3)) continue;
28988
+ queued2 = /"type"\s*:\s*"queue-operation"/.test(line3) && line3.includes('"enqueue"');
28989
+ if (!queued2 && !/"type"\s*:\s*"user"|"role"\s*:\s*"user"/.test(line3)) continue;
28919
28990
  text7 = visibleNativeUserText(leadingText(line3) ?? "");
28920
28991
  }
28921
28992
  if (!text7) continue;
28922
28993
  opening ??= text7;
28923
- if (!queued) {
28994
+ if (!queued2) {
28924
28995
  first2 = text7;
28925
28996
  break;
28926
28997
  }
@@ -34485,7 +34556,12 @@ function adoptHandedOverDraft() {
34485
34556
  } catch {
34486
34557
  }
34487
34558
  }
34488
- var byHome, forced, pinned, REEXEC_DRAFT_ENV;
34559
+ function adoptHandedOverTyped() {
34560
+ const text7 = process.env[REEXEC_TYPED_ENV];
34561
+ delete process.env[REEXEC_TYPED_ENV];
34562
+ return text7 || void 0;
34563
+ }
34564
+ var byHome, forced, pinned, REEXEC_DRAFT_ENV, REEXEC_TYPED_ENV;
34489
34565
  var init_ephemeral = __esm({
34490
34566
  "src/session/ephemeral.ts"() {
34491
34567
  "use strict";
@@ -34495,6 +34571,7 @@ var init_ephemeral = __esm({
34495
34571
  forced = /* @__PURE__ */ new Set();
34496
34572
  pinned = /* @__PURE__ */ new Set();
34497
34573
  REEXEC_DRAFT_ENV = "CLIKCODE_REEXEC_DRAFT";
34574
+ REEXEC_TYPED_ENV = "CLIKCODE_REEXEC_TYPED";
34498
34575
  }
34499
34576
  });
34500
34577
 
@@ -44587,7 +44664,7 @@ var init_route_models = __esm({
44587
44664
  });
44588
44665
 
44589
44666
  // src/agent/sandbox.ts
44590
- import { spawnSync as spawnSync2 } from "node:child_process";
44667
+ import { spawnSync } from "node:child_process";
44591
44668
  import { accessSync, constants as constants5, existsSync as existsSync8, realpathSync } from "node:fs";
44592
44669
  import os4 from "node:os";
44593
44670
  import path12 from "node:path";
@@ -44715,7 +44792,7 @@ function onPath(binary) {
44715
44792
  function sandboxAvailable(binary) {
44716
44793
  if (!onPath(binary)) return false;
44717
44794
  if (binary !== "bwrap") return true;
44718
- bwrapRuns ??= spawnSync2("bwrap", ["--ro-bind", "/", "/", "--dev", "/dev", "--proc", "/proc", "--", "/bin/true"], { stdio: "ignore", timeout: 5e3 }).status === 0;
44795
+ bwrapRuns ??= spawnSync("bwrap", ["--ro-bind", "/", "/", "--dev", "/dev", "--proc", "/proc", "--", "/bin/true"], { stdio: "ignore", timeout: 5e3 }).status === 0;
44719
44796
  return bwrapRuns;
44720
44797
  }
44721
44798
  function realOrSame(dir2) {
@@ -44732,14 +44809,14 @@ function realOrSame(dir2) {
44732
44809
  function platformDirs() {
44733
44810
  if (process.platform !== "darwin") return [];
44734
44811
  darwinDirs ??= ["DARWIN_USER_TEMP_DIR", "DARWIN_USER_CACHE_DIR"].flatMap((name) => {
44735
- const result = spawnSync2("/usr/bin/getconf", [name], { encoding: "utf8", timeout: 5e3 });
44812
+ const result = spawnSync("/usr/bin/getconf", [name], { encoding: "utf8", timeout: 5e3 });
44736
44813
  const dir2 = result.status === 0 ? result.stdout.trim() : "";
44737
44814
  return dir2 && path12.isAbsolute(dir2) ? [dir2] : [];
44738
44815
  });
44739
44816
  return darwinDirs;
44740
44817
  }
44741
44818
  function linkedWorktreeGit(cwd) {
44742
- const result = spawnSync2("git", ["rev-parse", "--path-format=absolute", "--git-dir", "--git-common-dir"], { cwd, encoding: "utf8", timeout: 5e3 });
44819
+ const result = spawnSync("git", ["rev-parse", "--path-format=absolute", "--git-dir", "--git-common-dir"], { cwd, encoding: "utf8", timeout: 5e3 });
44743
44820
  if (result.status !== 0) return { writable: [], readOnly: [] };
44744
44821
  const [gitDir, common2] = result.stdout.trim().split("\n");
44745
44822
  if (!gitDir || !common2 || gitDir === common2) return { writable: [], readOnly: [] };
@@ -47439,35 +47516,6 @@ var init_pending_prompt = __esm({
47439
47516
  }
47440
47517
  });
47441
47518
 
47442
- // src/tui/keys.ts
47443
- function environmentFlag2(...values) {
47444
- return values.some((value) => {
47445
- const normalized = (value ?? "").trim().toLowerCase();
47446
- return normalized === "1" || normalized === "true" || normalized === "yes" || normalized === "on";
47447
- });
47448
- }
47449
- function pastedText(key3) {
47450
- return key3.startsWith(PASTE_START) && key3.endsWith(PASTE_END) ? sanitizeTerminalText(key3.slice(PASTE_START.length, key3.length - PASTE_END.length)) : void 0;
47451
- }
47452
- function kittyKeyboardSafe(environment = process.env) {
47453
- if (environmentFlag2(environment.CLIKCODE_NO_KITTY_KEYBOARD)) return false;
47454
- if (environment.TMUX || environment.STY || /^(?:screen|tmux)/.test(environment.TERM ?? "")) return false;
47455
- const program3 = (environment.TERM_PROGRAM ?? "").toLowerCase();
47456
- return Boolean(environment.KITTY_WINDOW_ID || environment.GHOSTTY_RESOURCES_DIR || environment.WEZTERM_PANE || /^(?:xterm-kitty|xterm-ghostty|foot|alacritty|wezterm)/.test(environment.TERM ?? "") || program3 === "wezterm" || program3 === "ghostty" || program3 === "kitty");
47457
- }
47458
- var PASTE_START, PASTE_END, PUSH_KITTY_KEYBOARD, POP_KITTY_KEYBOARD, NEWLINE_KEY;
47459
- var init_keys = __esm({
47460
- "src/tui/keys.ts"() {
47461
- "use strict";
47462
- init_text();
47463
- PASTE_START = "\x1B[200~";
47464
- PASTE_END = "\x1B[201~";
47465
- PUSH_KITTY_KEYBOARD = "\x1B[>1u";
47466
- POP_KITTY_KEYBOARD = "\x1B[<u";
47467
- NEWLINE_KEY = "\x1B\r";
47468
- }
47469
- });
47470
-
47471
47519
  // src/tui/cursor-log.ts
47472
47520
  import { appendFileSync as appendFileSync4, mkdirSync as mkdirSync5, renameSync as renameSync2, statSync as statSync6 } from "node:fs";
47473
47521
  import { join as join87 } from "node:path";
@@ -47488,12 +47536,29 @@ function logCursorEvent(line3) {
47488
47536
  if (cursorLogLines >= FRAME_LOG_LINES) return;
47489
47537
  cursorLogLines += 1;
47490
47538
  }
47539
+ queued.push(`[${(/* @__PURE__ */ new Date()).toISOString()}] pid ${process.pid} ${line3}
47540
+ `);
47541
+ scheduleFlush();
47542
+ }
47543
+ function scheduleFlush() {
47544
+ if (!exitHooked2) {
47545
+ exitHooked2 = true;
47546
+ process.once("exit", flushCursorLog);
47547
+ }
47548
+ if (flushTimer) return;
47549
+ flushTimer = setTimeout(flushCursorLog, FLUSH_MS);
47550
+ flushTimer.unref();
47551
+ }
47552
+ function flushCursorLog() {
47553
+ if (flushTimer) clearTimeout(flushTimer);
47554
+ flushTimer = void 0;
47555
+ if (!queued.length) return;
47556
+ const text7 = queued.splice(0).join("");
47491
47557
  try {
47492
47558
  const dir2 = stateDirectory();
47493
47559
  mkdirSync5(dir2, { recursive: true });
47494
47560
  rotateIfLarge(join87(dir2, "cursor.log"));
47495
- appendFileSync4(join87(dir2, "cursor.log"), `[${(/* @__PURE__ */ new Date()).toISOString()}] pid ${process.pid} ${line3}
47496
- `, { encoding: "utf8", mode: 384 });
47561
+ appendFileSync4(join87(dir2, "cursor.log"), text7, { encoding: "utf8", mode: 384 });
47497
47562
  } catch {
47498
47563
  }
47499
47564
  }
@@ -47512,7 +47577,7 @@ function traceRawInput(chunk) {
47512
47577
  } catch {
47513
47578
  }
47514
47579
  }
47515
- var cursorLogLines, inputLogLines, FRAME_LOG_LINES, INPUT_LOG_LINES, ROTATE_BYTES2, ROTATE_CHECK_EVERY2, linesSinceCheck2, TRACE_LIMIT_BYTES, traceBytes, traceLast;
47580
+ var cursorLogLines, inputLogLines, FRAME_LOG_LINES, INPUT_LOG_LINES, ROTATE_BYTES2, ROTATE_CHECK_EVERY2, linesSinceCheck2, queued, FLUSH_MS, flushTimer, exitHooked2, TRACE_LIMIT_BYTES, traceBytes, traceLast;
47516
47581
  var init_cursor_log = __esm({
47517
47582
  "src/tui/cursor-log.ts"() {
47518
47583
  "use strict";
@@ -47524,6 +47589,9 @@ var init_cursor_log = __esm({
47524
47589
  ROTATE_BYTES2 = 5 * 1024 * 1024;
47525
47590
  ROTATE_CHECK_EVERY2 = 200;
47526
47591
  linesSinceCheck2 = ROTATE_CHECK_EVERY2;
47592
+ queued = [];
47593
+ FLUSH_MS = 1e3;
47594
+ exitHooked2 = false;
47527
47595
  TRACE_LIMIT_BYTES = 256 * 1024;
47528
47596
  traceBytes = 0;
47529
47597
  traceLast = 0;
@@ -47584,11 +47652,16 @@ var init_probe = __esm({
47584
47652
 
47585
47653
  // src/tui/modes.ts
47586
47654
  import { stdin as input4 } from "node:process";
47587
- function sessionModesOn(opening = false) {
47655
+ function mouseWanted(env3 = process.env) {
47656
+ return env3.CLIKCODE_MOUSE === "1" && !inlineHistoryMode(env3);
47657
+ }
47658
+ function sessionModesOn() {
47588
47659
  terminalModes.bracketedPaste = true;
47589
- terminalModes.wheelReporting = !SELECTION_MODE.active;
47590
- const mouse = SELECTION_MODE.active ? "" : opening ? OPENING_MOUSE_TRACKING() : ENABLE_MOUSE_TRACKING();
47591
- return `${ENABLE_BRACKETED_PASTE}${mouse}${FOCUS_REPORTING_ON}`;
47660
+ terminalModes.wheelReporting = mouseWanted() && !SELECTION_MODE.active;
47661
+ const mouse = SELECTION_MODE.active ? "" : ENABLE_MOUSE_TRACKING();
47662
+ const scroll = mouseWanted() || inlineHistoryMode() ? "" : ALTERNATE_SCROLL_ON;
47663
+ terminalModes.alternateScroll = scroll !== "";
47664
+ return `${ENABLE_BRACKETED_PASTE}${mouse}${scroll}${FOCUS_REPORTING_ON}`;
47592
47665
  }
47593
47666
  function sessionModesOff(leavingAlternateScreen) {
47594
47667
  terminalModes.bracketedPaste = false;
@@ -47624,7 +47697,7 @@ function enterInputModes() {
47624
47697
  sequence += ENABLE_BRACKETED_PASTE;
47625
47698
  terminalModes.bracketedPaste = true;
47626
47699
  }
47627
- if (!terminalModes.wheelReporting && !SELECTION_MODE.active) {
47700
+ if (!terminalModes.wheelReporting && !SELECTION_MODE.active && mouseWanted()) {
47628
47701
  sequence += ENABLE_MOUSE_TRACKING();
47629
47702
  terminalModes.wheelReporting = true;
47630
47703
  }
@@ -47641,6 +47714,9 @@ function popReadModes() {
47641
47714
  return POP_KITTY_KEYBOARD;
47642
47715
  }
47643
47716
  function setSelectionMode(active2) {
47717
+ if (!mouseWanted()) {
47718
+ return inlineHistoryMode() ? "The terminal's own selection is always on: select and copy as usual." : "The terminal's own selection is always on: select and copy as usual. PageUp, PageDown, Home, End and the arrows read the conversation back.";
47719
+ }
47644
47720
  SELECTION_MODE.active = active2;
47645
47721
  if (active2) {
47646
47722
  queuedModes += MOUSE_MODES_OFF;
@@ -47648,11 +47724,10 @@ function setSelectionMode(active2) {
47648
47724
  return "Selection mode on \u2014 select and copy with your terminal as usual. Swipe-scrolling is off until you run /select again.";
47649
47725
  }
47650
47726
  queuedModes += ENABLE_MOUSE_TRACKING();
47651
- terminalModes.wheelReporting = !inlineHistoryMode();
47652
- if (inlineHistoryMode()) return "Selection mode off.";
47727
+ terminalModes.wheelReporting = true;
47653
47728
  return "Selection mode off \u2014 swipe-scrolling is back.";
47654
47729
  }
47655
- var ENABLE_BRACKETED_PASTE, MOUSE_TRACKING_ON, OPENING_MOUSE_TRACKING_ON, ENABLE_MOUSE_TRACKING, OPENING_MOUSE_TRACKING, SELECTION_MODE, queuedModes, MOUSE_EVENT, LEGACY_MOUSE_PREFIX, LEGACY_MOUSE_EVENT, isMouseEvent, SWIPE_ROWS;
47730
+ var ENABLE_BRACKETED_PASTE, MOUSE_TRACKING_ON, ALTERNATE_SCROLL_ON, ENABLE_MOUSE_TRACKING, SELECTION_MODE, queuedModes, MOUSE_EVENT, LEGACY_MOUSE_PREFIX, LEGACY_MOUSE_EVENT, isMouseEvent, SWIPE_ROWS;
47656
47731
  var init_modes = __esm({
47657
47732
  "src/tui/modes.ts"() {
47658
47733
  "use strict";
@@ -47662,10 +47737,9 @@ var init_modes = __esm({
47662
47737
  init_cursor_log();
47663
47738
  init_inline();
47664
47739
  ENABLE_BRACKETED_PASTE = "\x1B[?2004h";
47665
- MOUSE_TRACKING_ON = "\x1B[?1000h\x1B[?1002h\x1B[?1003h\x1B[?1006h";
47666
- OPENING_MOUSE_TRACKING_ON = "\x1B[?1000h\x1B[?1002h\x1B[?1003h\x1B[?1006l\x1B[?1006h";
47667
- ENABLE_MOUSE_TRACKING = () => inlineHistoryMode() ? "" : MOUSE_TRACKING_ON;
47668
- OPENING_MOUSE_TRACKING = () => inlineHistoryMode() ? "" : OPENING_MOUSE_TRACKING_ON;
47740
+ MOUSE_TRACKING_ON = "\x1B[?1000h\x1B[?1002h\x1B[?1003h\x1B[?1006l\x1B[?1006h";
47741
+ ALTERNATE_SCROLL_ON = "\x1B[?1007h";
47742
+ ENABLE_MOUSE_TRACKING = () => mouseWanted() ? MOUSE_TRACKING_ON : "";
47669
47743
  SELECTION_MODE = { active: false };
47670
47744
  queuedModes = "";
47671
47745
  MOUSE_EVENT = /^\u001b\[<(\d+);\d+;\d+[Mm]$/;
@@ -47751,7 +47825,7 @@ function listenForTerminalKeys(onKey) {
47751
47825
  const owner = {};
47752
47826
  keyOwners.push(owner);
47753
47827
  const decoder = new TerminalInputDecoder();
47754
- let flushTimer;
47828
+ let flushTimer2;
47755
47829
  const deliver = (keys) => {
47756
47830
  keyBatchDepth += 1;
47757
47831
  try {
@@ -47783,18 +47857,18 @@ function listenForTerminalKeys(onKey) {
47783
47857
  };
47784
47858
  const onData = (chunk) => {
47785
47859
  if (keyOwners.at(-1) !== owner) {
47786
- if (flushTimer) clearTimeout(flushTimer);
47787
- flushTimer = void 0;
47860
+ if (flushTimer2) clearTimeout(flushTimer2);
47861
+ flushTimer2 = void 0;
47788
47862
  decoder.flush();
47789
47863
  return;
47790
47864
  }
47791
47865
  traceRawInput(chunk);
47792
- if (flushTimer) clearTimeout(flushTimer);
47866
+ if (flushTimer2) clearTimeout(flushTimer2);
47793
47867
  deliver(decoder.push(chunk));
47794
47868
  const delay2 = decoder.flushDelayMs();
47795
47869
  if (delay2 !== void 0) {
47796
- flushTimer = setTimeout(() => deliver(decoder.flush()), delay2);
47797
- flushTimer.unref();
47870
+ flushTimer2 = setTimeout(() => deliver(decoder.flush()), delay2);
47871
+ flushTimer2.unref();
47798
47872
  }
47799
47873
  };
47800
47874
  input5.on("data", onData);
@@ -47815,8 +47889,8 @@ function listenForTerminalKeys(onKey) {
47815
47889
  const at = keyOwners.indexOf(owner);
47816
47890
  if (at >= 0) keyOwners.splice(at, 1);
47817
47891
  readers -= 1;
47818
- if (flushTimer) clearTimeout(flushTimer);
47819
- flushTimer = void 0;
47892
+ if (flushTimer2) clearTimeout(flushTimer2);
47893
+ flushTimer2 = void 0;
47820
47894
  input5.off("data", onData);
47821
47895
  };
47822
47896
  }
@@ -47825,7 +47899,7 @@ function takeTerminalKeys(onKey) {
47825
47899
  input5.resume();
47826
47900
  return listenForTerminalKeys(onKey);
47827
47901
  }
47828
- var ESCAPE_SEQUENCE_TIMEOUT_MS, MAX_OSC_LENGTH, OPEN_PASTE_TIMEOUT_MS, FOCUS_EVENT, DEVICE_ATTRIBUTES_REPLY, PRIVATE_REPORT, readers, unread, unreadBytes, UNREAD_LIMIT, KEEP_STDIN_FLOWING, TerminalInputDecoder, CURSOR_POSITION_REPORT, cursorReports, keyBatchDepth, keyBatchEndListeners, focusListeners, keyOwners;
47902
+ var ESCAPE_SEQUENCE_TIMEOUT_MS, SLOW_LINK_ESCAPE_TIMEOUT_MS, REJOIN_WINDOW_MS, CSI_REMAINDER, SS3_REMAINDER, slowLink, MAX_OSC_LENGTH, OPEN_PASTE_TIMEOUT_MS, FOCUS_EVENT, DEVICE_ATTRIBUTES_REPLY, PRIVATE_REPORT, readers, unread, unreadBytes, UNREAD_LIMIT, KEEP_STDIN_FLOWING, TerminalInputDecoder, CURSOR_POSITION_REPORT, cursorReports, keyBatchDepth, keyBatchEndListeners, focusListeners, keyOwners;
47829
47903
  var init_input_decoder = __esm({
47830
47904
  "src/tui/input-decoder.ts"() {
47831
47905
  "use strict";
@@ -47835,11 +47909,16 @@ var init_input_decoder = __esm({
47835
47909
  init_probe();
47836
47910
  init_modes();
47837
47911
  ESCAPE_SEQUENCE_TIMEOUT_MS = 120;
47912
+ SLOW_LINK_ESCAPE_TIMEOUT_MS = 500;
47913
+ REJOIN_WINDOW_MS = 1e3;
47914
+ CSI_REMAINDER = /^\[[\d;:?<]*[@-~]?$/;
47915
+ SS3_REMAINDER = /^O[ABCDHF]$/;
47916
+ slowLink = false;
47838
47917
  MAX_OSC_LENGTH = 4096;
47839
47918
  OPEN_PASTE_TIMEOUT_MS = 1e4;
47840
47919
  FOCUS_EVENT = /^\u001b\[[IO]$/;
47841
47920
  DEVICE_ATTRIBUTES_REPLY = /^\u001b\[\?[0-9;]*c$/;
47842
- PRIVATE_REPORT = /^\u001b\[\?\d+(?:;\d+)*(?:\$y|t)$/;
47921
+ PRIVATE_REPORT = /^\u001b\[\?\d+(?:;\d+)*\$y$/;
47843
47922
  readers = 0;
47844
47923
  unread = [];
47845
47924
  unreadBytes = 0;
@@ -47852,10 +47931,34 @@ var init_input_decoder = __esm({
47852
47931
  TerminalInputDecoder = class {
47853
47932
  utf8 = new StringDecoder("utf8");
47854
47933
  pending = "";
47934
+ /** When a bare Esc was given up on at a flush (its sequence may still be on the wire). */
47935
+ loneEscAt;
47936
+ /** An unfinished `ESC [ ...` dropped at a flush, and when. */
47937
+ orphan;
47855
47938
  push(chunk) {
47856
- this.pending += typeof chunk === "string" ? chunk : this.utf8.write(chunk);
47939
+ const text7 = typeof chunk === "string" ? chunk : this.utf8.write(chunk);
47940
+ this.rejoin(text7);
47941
+ this.pending += text7;
47857
47942
  return this.drain(false);
47858
47943
  }
47944
+ /** A sequence whose first bytes were given up on and whose rest arrives within the window is one sequence: the rest is not
47945
+ * typed text. An unfinished `ESC [ ...` that was dropped is put back in front of it. A bare Esc already delivered cannot be
47946
+ * taken back, but the rest is read as the key it was and not typed as `[A`; and this link now waits longer for the next. */
47947
+ rejoin(text7) {
47948
+ const now = Date.now();
47949
+ const orphan = this.orphan;
47950
+ const lone = this.loneEscAt;
47951
+ this.orphan = void 0;
47952
+ this.loneEscAt = void 0;
47953
+ if (this.pending) return;
47954
+ if (orphan && now - orphan.at <= REJOIN_WINDOW_MS && !text7.startsWith("\x1B")) {
47955
+ this.pending = orphan.text;
47956
+ slowLink = true;
47957
+ } else if (lone !== void 0 && now - lone <= REJOIN_WINDOW_MS && (CSI_REMAINDER.test(text7) || SS3_REMAINDER.test(text7))) {
47958
+ this.pending = "\x1B";
47959
+ slowLink = true;
47960
+ }
47961
+ }
47859
47962
  flush() {
47860
47963
  this.pending += this.utf8.end();
47861
47964
  return this.drain(true);
@@ -47864,7 +47967,7 @@ var init_input_decoder = __esm({
47864
47967
  * pending, or undefined when nothing is. */
47865
47968
  flushDelayMs() {
47866
47969
  if (!this.pending) return void 0;
47867
- return this.pending.startsWith(PASTE_START) ? OPEN_PASTE_TIMEOUT_MS : ESCAPE_SEQUENCE_TIMEOUT_MS;
47970
+ return this.pending.startsWith(PASTE_START) ? OPEN_PASTE_TIMEOUT_MS : slowLink ? SLOW_LINK_ESCAPE_TIMEOUT_MS : ESCAPE_SEQUENCE_TIMEOUT_MS;
47868
47971
  }
47869
47972
  drain(flush) {
47870
47973
  const keys = [];
@@ -47879,6 +47982,7 @@ var init_input_decoder = __esm({
47879
47982
  if (flush) {
47880
47983
  keys.push("\x1B");
47881
47984
  this.pending = "";
47985
+ this.loneEscAt = Date.now();
47882
47986
  }
47883
47987
  break;
47884
47988
  }
@@ -47923,8 +48027,8 @@ var init_input_decoder = __esm({
47923
48027
  while (end < this.pending.length && !/[\x40-\x7e]/.test(this.pending[end])) end++;
47924
48028
  if (end >= this.pending.length) {
47925
48029
  if (flush) {
47926
- keys.push("\x1B");
47927
- this.pending = this.pending.slice(1);
48030
+ this.orphan = { text: this.pending, at: Date.now() };
48031
+ this.pending = "";
47928
48032
  continue;
47929
48033
  }
47930
48034
  break;
@@ -47936,8 +48040,8 @@ var init_input_decoder = __esm({
47936
48040
  if (prefix === "O") {
47937
48041
  if (this.pending.length < 3) {
47938
48042
  if (flush) {
47939
- keys.push("\x1B");
47940
- this.pending = this.pending.slice(1);
48043
+ this.orphan = { text: this.pending, at: Date.now() };
48044
+ this.pending = "";
47941
48045
  continue;
47942
48046
  }
47943
48047
  break;
@@ -47987,12 +48091,13 @@ var init_input_decoder = __esm({
47987
48091
  });
47988
48092
 
47989
48093
  // src/tui/prompter/state.ts
47990
- var EXIT_CONFIRM_MS, RESIZE_SETTLE_MS, SCROLL_DRAIN_MIN, SCROLL_DRAIN_MS, ALTERNATE_TRANSCRIPT_ROWS, SELECTION_SCROLL_MS, LIVE_OUTPUT_LINES, EMPTY_COMPOSER;
48094
+ var EXIT_CONFIRM_MS, RESIZE_SETTLE_MS, CURSOR_REPORT_MS, SCROLL_DRAIN_MIN, SCROLL_DRAIN_MS, ALTERNATE_TRANSCRIPT_ROWS, SELECTION_SCROLL_MS, LIVE_OUTPUT_LINES, EMPTY_COMPOSER;
47991
48095
  var init_state = __esm({
47992
48096
  "src/tui/prompter/state.ts"() {
47993
48097
  "use strict";
47994
48098
  EXIT_CONFIRM_MS = 2e3;
47995
48099
  RESIZE_SETTLE_MS = 100;
48100
+ CURSOR_REPORT_MS = 120;
47996
48101
  SCROLL_DRAIN_MIN = 4;
47997
48102
  SCROLL_DRAIN_MS = 16;
47998
48103
  ALTERNATE_TRANSCRIPT_ROWS = 2e3;
@@ -48002,6 +48107,43 @@ var init_state = __esm({
48002
48107
  }
48003
48108
  });
48004
48109
 
48110
+ // src/tui/prompter/history-dump.ts
48111
+ function resumeFrom(p, resume2, end) {
48112
+ const start2 = p.messageLines.get(resume2.message);
48113
+ if (start2 === void 0) {
48114
+ let first2 = Number.POSITIVE_INFINITY;
48115
+ for (const index of p.messageLines.keys()) first2 = Math.min(first2, index);
48116
+ return resume2.message < first2 ? 0 : end;
48117
+ }
48118
+ const next = p.messageLines.get(resume2.message + 1);
48119
+ return start2 + Math.min(resume2.into, (next ?? end) - start2);
48120
+ }
48121
+ function takeHistoryDump() {
48122
+ const trimmed = this.alternateTrimmed;
48123
+ const all = [...this.alternateTranscript, ...this.pendingFinished];
48124
+ let from = this.dumpedThrough === void 0 ? 0 : Math.max(0, this.dumpedThrough - trimmed);
48125
+ const resume2 = this.dumpResume;
48126
+ if (this.dumpedThrough === void 0 && resume2) {
48127
+ this.dumpResume = void 0;
48128
+ if (resume2.session === this.currentSession?.id) from = resumeFrom(this, resume2, trimmed + all.length) - trimmed;
48129
+ }
48130
+ this.dumpedThrough = trimmed + all.length;
48131
+ const fresh = all.slice(from);
48132
+ if (!fresh.length) return "";
48133
+ const shown2 = fresh.slice(-HISTORY_DUMP_ROWS);
48134
+ const cut = fresh.length - shown2.length;
48135
+ const note = cut > 0 ? [`\x1B[2m\u2026 ${cut} earlier row${cut === 1 ? "" : "s"} not shown; /resume reopens the whole conversation\x1B[0m`] : [];
48136
+ return `\x1B[?7h${[...note, ...shown2].map((row) => `${row}${ROW_END}`).join("")}`;
48137
+ }
48138
+ var HISTORY_DUMP_ROWS, ROW_END;
48139
+ var init_history_dump = __esm({
48140
+ "src/tui/prompter/history-dump.ts"() {
48141
+ "use strict";
48142
+ HISTORY_DUMP_ROWS = 2e3;
48143
+ ROW_END = "\x1B[0m\r\n";
48144
+ }
48145
+ });
48146
+
48005
48147
  // src/tui/prompter/terminal-lifecycle.ts
48006
48148
  import { stdin as input6, stdout as output9 } from "node:process";
48007
48149
  function retakeScreen() {
@@ -48052,7 +48194,8 @@ function suspendToShell() {
48052
48194
  this.responsePaintTimer = void 0;
48053
48195
  this.pendingLive = void 0;
48054
48196
  setTerminalRawMode(false);
48055
- output9.write(`${eraseInlineBlock()}${sessionModesOff(true)}`);
48197
+ const paged = inlineBlock.page;
48198
+ output9.write(`${leavePage()}${eraseInlineBlock()}${sessionModesOff(!paged)}${historyDumpSequence()}`);
48056
48199
  terminalModes.alternateScreen = false;
48057
48200
  process.once("SIGCONT", this.onContinue);
48058
48201
  process.kill(process.pid, "SIGTSTP");
@@ -48089,7 +48232,7 @@ function close() {
48089
48232
  process.off("exit", restoreTerminal);
48090
48233
  setTerminalRawMode(false);
48091
48234
  input6.pause();
48092
- giveBackTerminal(`${eraseInlineBlock()}${popReadModes()}`);
48235
+ giveBackTerminal(`${leavePage()}${eraseInlineBlock()}${popReadModes()}`);
48093
48236
  }
48094
48237
  async function suspend() {
48095
48238
  lifecycle("window.suspend");
@@ -48100,8 +48243,10 @@ async function suspend() {
48100
48243
  this.responsePaintTimer = void 0;
48101
48244
  setTerminalRawMode(false);
48102
48245
  input6.pause();
48246
+ const paged = inlineBlock.page;
48103
48247
  await new Promise((resolveWritten) => {
48104
- output9.write(`${eraseInlineBlock()}${sessionModesOff(false)}`, () => resolveWritten());
48248
+ output9.write(`${leavePage()}${eraseInlineBlock()}${sessionModesOff(!paged)}${historyDumpSequence()}`, () => resolveWritten());
48249
+ terminalModes.alternateScreen = false;
48105
48250
  });
48106
48251
  }
48107
48252
  function resume() {
@@ -50172,7 +50317,10 @@ function schedulePaint(delay2 = PAINT_COALESCE_MS) {
50172
50317
  if (this.responsePaintTimer || this.closed || this.suspended || this.selecting || this.paletteActive) return;
50173
50318
  this.responsePaintTimer = setTimeout(() => {
50174
50319
  this.responsePaintTimer = void 0;
50175
- if (this.resizePaintTimer) return;
50320
+ if (this.resizePaintTimer) {
50321
+ this.paintDropped = true;
50322
+ return;
50323
+ }
50176
50324
  if (!this.closed && !this.selecting && !this.paletteActive) {
50177
50325
  if (this.turn) this.paintWaiting(this.turn);
50178
50326
  else this.repaint();
@@ -50184,7 +50332,11 @@ function flushPaint() {
50184
50332
  if (!this.responsePaintTimer) return;
50185
50333
  clearTimeout(this.responsePaintTimer);
50186
50334
  this.responsePaintTimer = void 0;
50187
- if (this.closed || this.suspended || this.selecting || this.paletteActive || this.resizePaintTimer) return;
50335
+ if (this.closed || this.suspended || this.selecting || this.paletteActive) return;
50336
+ if (this.resizePaintTimer) {
50337
+ this.paintDropped = true;
50338
+ return;
50339
+ }
50188
50340
  if (this.turn) this.paintWaiting(this.turn);
50189
50341
  else this.repaint();
50190
50342
  }
@@ -50260,7 +50412,17 @@ function onWaitingKey(key3) {
50260
50412
  this.flushPaint();
50261
50413
  return;
50262
50414
  }
50263
- if (!this.pendingApproval && this.handleScrollKey(key3)) return;
50415
+ if (this.handleScrollKey(key3)) return;
50416
+ if (this.pendingApproval && !this.pendingApproval.question && !this.tellingInstead) {
50417
+ if (key3 === "\x1B[A" || key3 === "\x1B[B") {
50418
+ if (!this.scrollTranscript(key3 === "\x1B[A" ? SWIPE_ROWS : -SWIPE_ROWS) && key3 === "\x1B[B") this.noteReadingDirection();
50419
+ return;
50420
+ }
50421
+ if (key3 === "" || key3 === "") {
50422
+ this.scrollTranscript(key3 === "" ? Number.MAX_SAFE_INTEGER : -Number.MAX_SAFE_INTEGER);
50423
+ return;
50424
+ }
50425
+ }
50264
50426
  if (!this.pendingApproval && key3 === "\x1B" && this.scrolledBack) {
50265
50427
  this.scrollTranscript(-Number.MAX_SAFE_INTEGER);
50266
50428
  return;
@@ -50279,14 +50441,14 @@ function onWaitingKey(key3) {
50279
50441
  let stopWithApproval = false;
50280
50442
  if (this.pendingApproval && (key3 === "\x1B" || key3 === "")) {
50281
50443
  this.restoreTellingDraft();
50282
- for (const queued of this.approvalQueue.splice(0)) queued.resolve(false);
50444
+ for (const queued2 of this.approvalQueue.splice(0)) queued2.resolve(false);
50283
50445
  this.answerApproval(this.pendingApproval, false);
50284
50446
  stopWithApproval = true;
50285
50447
  } else if (this.pendingApproval) {
50286
50448
  approvalKey.call(this, turn, this.pendingApproval, key3);
50287
50449
  return;
50288
50450
  }
50289
- if ((key3 === "\x1B[A" || key3 === "\x1B[B") && !turn.draft) {
50451
+ if ((key3 === "\x1B[A" || key3 === "\x1B[B") && (!turn.draft || this.scrolledBack)) {
50290
50452
  if (this.scrollTranscript(key3 === "\x1B[A" ? SWIPE_ROWS : -SWIPE_ROWS)) return;
50291
50453
  if (key3 === "\x1B[B") this.noteReadingDirection();
50292
50454
  return;
@@ -51242,6 +51404,12 @@ function onResize() {
51242
51404
  if (!this.closed) {
51243
51405
  logCursorEvent(`resize screen=${output13.columns}x${output13.rows} raw=${terminalModes.rawMode} alternate=${terminalModes.alternateScreen}`);
51244
51406
  this.requestRedraw("resize");
51407
+ if (!inlineHistoryMode() && !this.suspended && !this.resizePaintTimer) {
51408
+ this.rewrapIfWidthChanged();
51409
+ this.forgetScreenPosition();
51410
+ this.repaint();
51411
+ this.resizeSettled = true;
51412
+ } else this.resizeSettled = false;
51245
51413
  this.repaintAfterResize();
51246
51414
  }
51247
51415
  }
@@ -51251,6 +51419,12 @@ function repaintAfterResize() {
51251
51419
  this.resizePaintTimer = void 0;
51252
51420
  lifecycle("window.resize", { cols: output13.columns, rows: output13.rows });
51253
51421
  if (this.closed || this.suspended) return;
51422
+ const dropped = this.paintDropped;
51423
+ this.paintDropped = false;
51424
+ if (this.resizeSettled && !inlineHistoryMode()) {
51425
+ if (dropped) this.repaint();
51426
+ return;
51427
+ }
51254
51428
  const rewritten = this.rewrapIfWidthChanged();
51255
51429
  this.forgetScreenPosition();
51256
51430
  if (inlineHistoryMode() && !rewritten) this.anchorBlock();
@@ -51283,15 +51457,30 @@ function anchorBlock() {
51283
51457
  if (this.closed || this.suspended) return;
51284
51458
  this.repaint();
51285
51459
  };
51286
- askCursorRow(done);
51460
+ askCursorRow(done, CURSOR_REPORT_MS);
51461
+ }
51462
+ function dumpPlace(p) {
51463
+ const end = p.dumpedThrough;
51464
+ let message2;
51465
+ let line3 = 0;
51466
+ for (const [index, start2] of p.messageLines) if (start2 < end && (message2 === void 0 || index > message2)) {
51467
+ message2 = index;
51468
+ line3 = start2;
51469
+ }
51470
+ if (message2 === void 0) return void 0;
51471
+ return { session: p.currentSession?.id, message: message2, into: end - line3 };
51287
51472
  }
51288
51473
  function clearTranscript() {
51289
51474
  this.alternateTrimmed += this.alternateTranscript.length;
51290
51475
  this.alternateTranscript.length = 0;
51476
+ this.capDropped = 0;
51477
+ this.capMarkerLine = void 0;
51291
51478
  this.pendingFinished = [];
51292
51479
  this.lastFinishedRow = void 0;
51293
51480
  this.secondLastFinishedRow = void 0;
51294
51481
  this.alternateScrollback = 0;
51482
+ this.dumpResume = this.dumpedThrough === void 0 ? this.dumpResume : dumpPlace(this);
51483
+ this.dumpedThrough = void 0;
51295
51484
  if (inlineHistoryMode()) inlineBlock.clearNext = true;
51296
51485
  this.messageLines.clear();
51297
51486
  this.lineTags.clear();
@@ -51493,6 +51682,9 @@ var init_glyphs = __esm({
51493
51682
 
51494
51683
  // src/tui/prompter/frame-flush.ts
51495
51684
  import { stdout as output15 } from "node:process";
51685
+ function earlierRowsNotice(count2) {
51686
+ return `\x1B[2m\u2026 ${count2} earlier row${count2 === 1 ? "" : "s"} not shown; /resume reopens the whole conversation\x1B[0m`;
51687
+ }
51496
51688
  function safeRow(row, limit) {
51497
51689
  const clean2 = sanitizeTerminalText(row, { keepSgr: true, singleLine: true });
51498
51690
  return closeOpenHyperlink(visibleSlice(asciiMode() ? foldAscii(clean2) : clean2, limit));
@@ -51547,8 +51739,12 @@ function flushAlternateFrame(finished, pending4) {
51547
51739
  focusLine === void 0 ? Number.POSITIVE_INFINITY : focusLine - this.alternateTrimmed
51548
51740
  );
51549
51741
  if (excess > 0) {
51742
+ const markerWasFirst = this.capMarkerLine === this.alternateTrimmed;
51550
51743
  this.alternateTranscript.splice(0, excess);
51551
51744
  this.alternateTrimmed += excess;
51745
+ this.capDropped += excess - (markerWasFirst ? 1 : 0) + 1;
51746
+ this.alternateTranscript[0] = earlierRowsNotice(this.capDropped);
51747
+ this.capMarkerLine = this.alternateTrimmed;
51552
51748
  }
51553
51749
  }
51554
51750
  const extra = this.viewExtra;
@@ -51600,13 +51796,14 @@ function flushAlternateFrame(finished, pending4) {
51600
51796
  }
51601
51797
  }
51602
51798
  const full = this.alternatePrevious.length !== rows.length;
51603
- const scrolling = this.paintingScroll;
51799
+ const scrolling = this.paintingScroll || finished.length > 0 && !swallowsAlternateScreen();
51604
51800
  this.paintingScroll = false;
51605
51801
  const moving = Math.min(above, aboveBefore);
51606
51802
  const shift = full || !scrolling ? 0 : scrollShift(this.alternatePrevious, rows, moving);
51607
51803
  const updates = [];
51608
51804
  let exposedFrom = -1;
51609
51805
  let exposedTo = -1;
51806
+ let drawnRows = 0;
51610
51807
  if (shift !== 0) {
51611
51808
  const span2 = Math.abs(shift);
51612
51809
  updates.push(`\x1B[1;${moving}r`);
@@ -51617,6 +51814,7 @@ function flushAlternateFrame(finished, pending4) {
51617
51814
  exposedTo = exposedFrom + span2;
51618
51815
  for (const [offset, row] of exposed.entries()) {
51619
51816
  updates.push(`\x1B[${exposedFrom + offset + 1};1H${row}\x1B[K`);
51817
+ drawnRows += 1;
51620
51818
  }
51621
51819
  }
51622
51820
  for (const [index, row] of rows.entries()) {
@@ -51624,6 +51822,7 @@ function flushAlternateFrame(finished, pending4) {
51624
51822
  if (index >= exposedFrom && index < exposedTo) continue;
51625
51823
  if (shift !== 0 && index < moving && shiftedRow(this.alternatePrevious, index, shift) === row) continue;
51626
51824
  updates.push(`\x1B[${index + 1};1H${row}\x1B[K`);
51825
+ drawnRows += 1;
51627
51826
  }
51628
51827
  this.alternatePrevious = rows;
51629
51828
  const composerRow = rows.length - live2.length + pending4.cursorRow + 1;
@@ -51637,8 +51836,9 @@ function flushAlternateFrame(finished, pending4) {
51637
51836
  const draw = updates.length ? `${redrawPreamble(redraw)}${updates.join("")}` : "";
51638
51837
  if (updates.length && redraw === this.pendingRedraw) this.pendingRedraw = void 0;
51639
51838
  const visibleBefore = updates.length > 0 && redraw !== void 0 ? false : this.cursorShown;
51640
- const hideFirst = !showCursor && visibleBefore !== false ? "\x1B[?25l" : "";
51641
- const cursor = showCursor && visibleBefore !== true ? "\x1B[?25h" : "";
51839
+ const bulk = drawnRows > BULK_ROWS;
51840
+ const hideFirst = (!showCursor || bulk) && visibleBefore !== false ? "\x1B[?25l" : "";
51841
+ const cursor = showCursor && (visibleBefore !== true || hideFirst !== "") ? "\x1B[?25h" : "";
51642
51842
  const frame = `${syncBegin()}${modes}${signals}${hideFirst}${draw}${park2}${cursor}${syncEnd()}`;
51643
51843
  this.lastPark = park2;
51644
51844
  this.cursorShown = showCursor;
@@ -51655,10 +51855,6 @@ function flushInlineFrame(finished, pending4) {
51655
51855
  const overlay2 = this.pickerOverlay;
51656
51856
  const chrome = this.chromeRows;
51657
51857
  const page = chrome > 0 && pending4.live.length >= chrome && (this.surface === "history" || overlay2.length > 0);
51658
- if (page && !inlineBlock.page) {
51659
- const above = Math.max(0, inlineBlock.height - inlineBlock.rows - inlineBlock.slack - inlineBlock.pad);
51660
- inlineBlock.tail = inlineBlock.rows > 0 && above > 0 ? this.alternateTranscript.slice(-above) : [];
51661
- }
51662
51858
  if (finished.length) {
51663
51859
  this.alternateTranscript.push(...finished);
51664
51860
  const excess = this.alternateTranscript.length - ALTERNATE_TRANSCRIPT_ROWS;
@@ -51679,26 +51875,35 @@ function flushInlineFrame(finished, pending4) {
51679
51875
  live2 = [...live2.slice(0, at), ...overlay2.map((row) => safeRow(row, limit)), ...live2.slice(at)];
51680
51876
  if (cursorRow >= at) cursorRow += overlay2.length;
51681
51877
  }
51878
+ const dropTail = inlineBlock.clearNext;
51682
51879
  const leaving = inlineBlock.page;
51683
- const keptTail = leaving && !inlineBlock.clearNext ? inlineBlock.tail : [];
51684
- inlineBlock.page = false;
51880
+ let leave = "";
51881
+ if (leaving) {
51882
+ const resizedWhile = inlineBlock.resized;
51883
+ if (inlineBlock.wipe) inlineBlock.clearNext = true;
51884
+ restoreMainBlock();
51885
+ inlineBlock.resized = false;
51886
+ inlineBlock.wipe = false;
51887
+ terminalModes.alternateScreen = false;
51888
+ leave = LEAVE_PAGE_SCREEN;
51889
+ if (resizedWhile && !inlineBlock.clearNext && inlineBlock.rows > 0) {
51890
+ inlineBlock.tail = [...inlineBlock.tail, ...finished];
51891
+ output15.write(`${syncBegin()}${leave}${syncEnd()}`);
51892
+ this.anchorBlock();
51893
+ return;
51894
+ }
51895
+ }
51896
+ const carried = dropTail ? [] : inlineBlock.tail;
51685
51897
  inlineBlock.tail = [];
51898
+ const retired = carried.length ? [...carried, ...finished] : finished;
51686
51899
  const wipe = inlineBlock.clearNext;
51687
- const clear = wipe || leaving;
51900
+ const clear = wipe || leaving && inlineBlock.rows === 0;
51688
51901
  inlineBlock.clearNext = false;
51689
51902
  const anchored = !clear && inlineBlock.rows > 0;
51690
51903
  const found = anchored ? inlineBlock.found : void 0;
51691
51904
  inlineBlock.found = void 0;
51692
- const moved = found === void 0 ? 0 : inlineBlock.height - inlineBlock.rows - inlineBlock.slack - found;
51693
- const overSaved = inlineBlock.padOverSaved;
51694
- const blanksOnly = moved > 0 && moved <= inlineBlock.pad && !overSaved;
51695
- if (anchored) {
51696
- const spacer = Math.max(0, inlineBlock.rows - finished.length - live2.length);
51697
- if (spacer) {
51698
- live2 = [...Array(spacer).fill(""), ...live2];
51699
- cursorRow += spacer;
51700
- }
51701
- }
51905
+ const lost = anchored && inlineBlock.lost;
51906
+ inlineBlock.lost = false;
51702
51907
  if (live2.length > height) {
51703
51908
  cursorRow -= live2.length - height;
51704
51909
  live2 = live2.slice(-height);
@@ -51708,30 +51913,19 @@ function flushInlineFrame(finished, pending4) {
51708
51913
  this.frameLayout = { live: [...live2], tags: pending4.tags?.slice(-height) ?? [] };
51709
51914
  const showCursor = !pending4.hideCursor;
51710
51915
  const signature2 = JSON.stringify([live2, cursorRow, pending4.cursorColumn, showCursor]);
51711
- const modes = takeQueuedModes();
51916
+ const modes = `${leave}${takeQueuedModes()}`;
51712
51917
  const signals = this.pendingSignals;
51713
51918
  this.pendingSignals = "";
51714
- const lost = anchored && inlineBlock.lost;
51715
- inlineBlock.lost = false;
51716
- if (!clear && !lost && !finished.length && !modes && !signals && signature2 === inlineBlock.last) {
51717
- if (found === void 0) return;
51718
- const gap = height - found - inlineBlock.rows;
51719
- if (!blanksOnly && gap === 0) {
51720
- inlineBlock.height = height;
51721
- inlineBlock.pad = Math.max(0, inlineBlock.pad - Math.max(0, moved));
51722
- if (inlineBlock.pad === 0) inlineBlock.padOverSaved = false;
51723
- return;
51724
- }
51725
- }
51919
+ const resized = found !== void 0 || lost;
51920
+ if (!clear && !resized && !retired.length && !modes && !signals && signature2 === inlineBlock.last) return;
51726
51921
  const previous = inlineBlock.liveRows;
51727
51922
  const columns3 = output15.columns || 100;
51728
- const diff = anchored && !lost && found === void 0 && !finished.length && previous.length === inlineBlock.rows && inlineBlock.columns === columns3;
51923
+ const diff = anchored && !resized && !retired.length && previous.length === inlineBlock.rows && inlineBlock.columns === columns3;
51729
51924
  let lead = "";
51730
51925
  let text7 = "";
51731
51926
  let park2;
51732
- let nextPad = Math.max(0, inlineBlock.pad - Math.max(0, moved));
51733
- let nextSlack = 0;
51734
- let padOverSaved = overSaved;
51927
+ let nextPad = resized ? 0 : inlineBlock.pad;
51928
+ let top2 = inlineBlock.top;
51735
51929
  if (diff) {
51736
51930
  let at = inlineBlock.cursorRow;
51737
51931
  const move = (to) => {
@@ -51739,11 +51933,12 @@ function flushInlineFrame(finished, pending4) {
51739
51933
  at = to;
51740
51934
  return step < 0 ? `\x1B[${-step}A` : step > 0 ? `\x1B[${step}B` : "";
51741
51935
  };
51742
- if (live2.length > previous.length && nextPad > 0) {
51743
- const top2 = height - previous.length - inlineBlock.slack;
51744
- const take = Math.min(live2.length - previous.length, nextPad);
51936
+ const scrolls = Math.max(0, top2 + live2.length - height);
51937
+ if (live2.length > previous.length && scrolls > 0 && nextPad > 0) {
51938
+ const take = Math.min(scrolls, nextPad);
51745
51939
  text7 += `${top2 + at > 0 ? `\x1B[${top2 + at}A` : ""}\x1B[${take}M`;
51746
51940
  at = -(top2 - take);
51941
+ top2 -= take;
51747
51942
  nextPad -= take;
51748
51943
  }
51749
51944
  const common2 = Math.min(previous.length, live2.length);
@@ -51755,48 +51950,44 @@ function flushInlineFrame(finished, pending4) {
51755
51950
  for (let index = previous.length; index < live2.length; index += 1) text7 += `\r
51756
51951
  ${live2[index]}\x1B[K`;
51757
51952
  at = live2.length - 1;
51758
- nextSlack = Math.max(0, inlineBlock.slack - (live2.length - previous.length));
51759
- } else nextSlack = inlineBlock.slack;
51953
+ top2 = Math.min(top2, height - live2.length);
51954
+ } else if (live2.length < previous.length) {
51955
+ text7 += `${move(live2.length)}\r\x1B[J`;
51956
+ }
51760
51957
  park2 = `${move(cursorRow)}\x1B[${Math.max(1, pending4.cursorColumn)}G`;
51761
51958
  } else {
51762
- const oldTop = lost ? void 0 : anchored ? found ?? inlineBlock.height - inlineBlock.rows - inlineBlock.slack : void 0;
51763
- if (lost) {
51764
- nextPad = 0;
51765
- nextSlack = 0;
51766
- }
51959
+ const body = [...retired, ...live2];
51960
+ let amount = 0;
51767
51961
  if (clear) {
51768
51962
  lead = wipe ? CLEAR_SCREEN_AND_SCROLLBACK : CLEAR_SCREEN;
51769
51963
  inlineBlock.rows = 0;
51770
51964
  inlineBlock.cursorRow = 0;
51771
- } else lead = eraseInlineBlock();
51772
- const body = [...keptTail, ...finished, ...live2];
51773
- if (clear) {
51774
51965
  nextPad = Math.max(0, height - body.length);
51775
51966
  if (nextPad > 0) lead += `\x1B[${nextPad + 1};1H`;
51776
- } else if (oldTop !== void 0) {
51777
- const amount = Math.min(Math.max(0, oldTop + body.length - height), nextPad);
51967
+ top2 = nextPad;
51968
+ } else {
51969
+ if (found !== void 0) {
51970
+ const up = Math.max(0, inlineBlock.cursorRow + Math.min(0, found));
51971
+ lead = inlineBlock.rows ? `${up > 0 ? `\x1B[${up}A` : ""}\r\x1B[J` : "";
51972
+ eraseInlineBlock();
51973
+ top2 = Math.max(0, found);
51974
+ } else lead = eraseInlineBlock();
51975
+ amount = Math.min(Math.max(0, top2 + body.length - height), nextPad);
51778
51976
  if (amount > 0) {
51779
- lead += `${oldTop > 0 ? `\x1B[${oldTop}A` : ""}\x1B[${amount}M`;
51780
- const to = oldTop - amount;
51781
- if (to > 0) lead += `\x1B[${to}B`;
51977
+ lead += `${top2 > 0 ? `\x1B[${top2}A` : ""}\x1B[${amount}M`;
51978
+ if (top2 - amount > 0) lead += `\x1B[${top2 - amount}B`;
51782
51979
  nextPad -= amount;
51980
+ top2 -= amount;
51783
51981
  }
51784
- const gap = height - oldTop - body.length;
51785
- if (gap > 0) {
51786
- lead += `\x1B[1;1H\x1B[${gap}L\x1B[${oldTop + gap + 1};1H`;
51787
- if (nextPad === 0) padOverSaved = true;
51788
- nextPad += gap;
51789
- }
51790
- if (blanksOnly) lead += "\x1B[3J";
51791
51982
  }
51983
+ top2 = Math.min(top2 + body.length - live2.length, height - live2.length);
51792
51984
  text7 = body.map((row, index) => `${row}\x1B[K${index < body.length - 1 ? "\r\n" : ""}`).join("");
51793
51985
  const back = lastRow - cursorRow;
51794
51986
  park2 = `${back ? `\x1B[${back}A` : ""}\x1B[${Math.max(1, pending4.cursorColumn)}G`;
51795
51987
  }
51796
51988
  inlineBlock.pad = nextPad;
51797
- inlineBlock.padOverSaved = nextPad > 0 && padOverSaved && !clear && !lost;
51798
- inlineBlock.slack = nextSlack;
51799
- if (!anchored || found !== void 0 || lost) inlineBlock.height = height;
51989
+ inlineBlock.top = top2;
51990
+ inlineBlock.height = height;
51800
51991
  inlineBlock.rows = live2.length;
51801
51992
  inlineBlock.cursorRow = cursorRow;
51802
51993
  inlineBlock.last = signature2;
@@ -51808,7 +51999,7 @@ ${live2[index]}\x1B[K`;
51808
51999
  const frame = `${syncBegin()}${modes}${signals}\x1B[?25l\x1B[?7l${lead}${text7}${park2}${showCursor ? "\x1B[?25h" : ""}${syncEnd()}`;
51809
52000
  this.frameInFlight = true;
51810
52001
  terminalModes.painted = true;
51811
- logCursorEvent(`inline frame: block=${live2.length} finished=${finished.length} composer=${cursorRow} col=${pending4.cursorColumn}`);
52002
+ logCursorEvent(`inline frame: block=${live2.length} finished=${retired.length} composer=${cursorRow} col=${pending4.cursorColumn}`);
51812
52003
  output15.write(frame, () => {
51813
52004
  this.frameInFlight = false;
51814
52005
  if (this.pendingLive && !this.closed && !this.suspended) this.flushFrame();
@@ -51824,20 +52015,32 @@ function flushInlinePage(finished, pending4, height) {
51824
52015
  const blank = Math.max(0, height - rows.length);
51825
52016
  rows.splice(rows.length - footer.length, 0, ...Array(blank).fill(""));
51826
52017
  const cursorRow = Math.max(0, Math.min(rows.length - 1, rows.length - footer.length + Math.max(0, pending4.cursorRow - at)));
51827
- const resized = inlineBlock.page && (inlineBlock.height !== height || inlineBlock.columns !== columns3);
51828
- const fresh = !inlineBlock.page || resized || inlineBlock.clearNext;
52018
+ const opening = !inlineBlock.page;
52019
+ if (opening) {
52020
+ const { rows: blockRows, cursorRow: blockCursor, last: last2, liveRows, pad: pad3, top: top2, height: blockHeight, columns: blockColumns } = inlineBlock;
52021
+ inlineBlock.main = { rows: blockRows, cursorRow: blockCursor, last: last2, liveRows: [...liveRows], pad: pad3, top: top2, height: blockHeight, columns: blockColumns };
52022
+ inlineBlock.tail = [];
52023
+ inlineBlock.resized = false;
52024
+ inlineBlock.wipe = false;
52025
+ terminalModes.alternateScreen = true;
52026
+ }
52027
+ const resized = !opening && (inlineBlock.height !== height || inlineBlock.columns !== columns3);
52028
+ if (resized) inlineBlock.resized = true;
52029
+ const fresh = opening || resized || inlineBlock.clearNext;
51829
52030
  const showCursor = !pending4.hideCursor;
51830
52031
  const signature2 = JSON.stringify([rows, cursorRow, pending4.cursorColumn, showCursor]);
51831
52032
  const modes = takeQueuedModes();
51832
52033
  const signals = this.pendingSignals;
51833
52034
  this.pendingSignals = "";
51834
- inlineBlock.tail.push(...finished);
51835
- if (resized || inlineBlock.clearNext) this.emitted.requestReseed();
52035
+ if (inlineBlock.clearNext) {
52036
+ inlineBlock.wipe = true;
52037
+ inlineBlock.tail = [...finished];
52038
+ } else inlineBlock.tail.push(...finished);
51836
52039
  if (!fresh && !modes && !signals && signature2 === inlineBlock.last) return;
51837
52040
  const previous = fresh ? [] : inlineBlock.liveRows;
51838
52041
  let text7 = "";
51839
52042
  for (const [index, row] of rows.entries()) if (previous[index] !== row) text7 += `\x1B[${index + 1};1H${row}\x1B[K`;
51840
- const lead = resized || inlineBlock.clearNext ? CLEAR_SCREEN_AND_SCROLLBACK : fresh ? CLEAR_SCREEN : "";
52043
+ const lead = opening ? ENTER_PAGE_SCREEN : fresh ? CLEAR_SCREEN : "";
51841
52044
  const park2 = `\x1B[${cursorRow + 1};${Math.max(1, pending4.cursorColumn)}H`;
51842
52045
  this.frameLayout = { live: [...rows], tags: [] };
51843
52046
  inlineBlock.clearNext = false;
@@ -51849,7 +52052,7 @@ function flushInlinePage(finished, pending4, height) {
51849
52052
  inlineBlock.columns = columns3;
51850
52053
  inlineBlock.height = height;
51851
52054
  inlineBlock.pad = 0;
51852
- inlineBlock.slack = 0;
52055
+ inlineBlock.top = 0;
51853
52056
  inlineBlock.found = void 0;
51854
52057
  inlineBlock.lost = false;
51855
52058
  this.pendingRedraw = void 0;
@@ -51864,6 +52067,7 @@ function flushInlinePage(finished, pending4, height) {
51864
52067
  if (this.pendingLive && !this.closed && !this.suspended) this.flushFrame();
51865
52068
  });
51866
52069
  }
52070
+ var BULK_ROWS;
51867
52071
  var init_frame_flush = __esm({
51868
52072
  "src/tui/prompter/frame-flush.ts"() {
51869
52073
  "use strict";
@@ -51880,6 +52084,7 @@ var init_frame_flush = __esm({
51880
52084
  init_modes();
51881
52085
  init_state();
51882
52086
  init_group_actions();
52087
+ BULK_ROWS = 8;
51883
52088
  }
51884
52089
  });
51885
52090
 
@@ -52643,6 +52848,8 @@ var init_prompt_input = __esm({
52643
52848
  cursor;
52644
52849
  selected = 0;
52645
52850
  historyIndex;
52851
+ /** The draft as typed, kept while history is recalled over it (at index `history.length`), so Down past the newest entry restores it. */
52852
+ stashedDraft;
52646
52853
  // Long pastes, held out of the draft as placeholders (held-pastes.ts)
52647
52854
  // and put back when it is sent.
52648
52855
  held = [];
@@ -52840,6 +53047,7 @@ ${kept}` : kept;
52840
53047
  this.held = [];
52841
53048
  this.selected = 0;
52842
53049
  this.historyIndex = p.history.length;
53050
+ this.stashedDraft = void 0;
52843
53051
  this.draw();
52844
53052
  return true;
52845
53053
  }
@@ -52909,17 +53117,31 @@ ${kept}` : kept;
52909
53117
  return false;
52910
53118
  }
52911
53119
  historyStep(direction) {
53120
+ const live2 = this.p.history.length;
53121
+ if (direction < 0 && this.historyIndex === live2 && this.historyIndex > 0) this.stashedDraft = { value: this.value, cursor: this.cursor, held: [...this.held] };
52912
53122
  if (direction < 0 && this.historyIndex > 0) this.historyIndex -= 1;
52913
- else if (direction > 0) this.historyIndex = Math.min(this.p.history.length, this.historyIndex + 1);
53123
+ else if (direction > 0) this.historyIndex = Math.min(live2, this.historyIndex + 1);
52914
53124
  else return;
53125
+ if (this.historyIndex === live2) {
53126
+ const draft = this.stashedDraft;
53127
+ this.stashedDraft = void 0;
53128
+ if (draft) {
53129
+ this.apply(draft);
53130
+ return;
53131
+ }
53132
+ }
52915
53133
  this.value = this.p.history[this.historyIndex] ?? "";
52916
53134
  this.cursor = this.value.length;
52917
53135
  }
52918
53136
  /** Arrows and history keys: true when the key was handled here.
52919
53137
  * Up/Down navigate palette options; otherwise they move through a
52920
53138
  * multi-line draft and fall through to input history from its first
52921
- * and last line. (Wheel/touch scrolling belongs to the terminal and
52922
- * never arrives as these keys.) Ctrl+P/Ctrl+N always mean history. */
53139
+ * and last line. With the composer empty, or the view already scrolled
53140
+ * back, they read the conversation instead: a swipe or wheel notch reaches
53141
+ * the program as these keys (alternate scroll, `?1007`) and cannot be told
53142
+ * from typing them. Recalling history over a draft keeps the draft (Down
53143
+ * past the newest entry brings it back). Ctrl+P/Ctrl+N always mean
53144
+ * history. */
52923
53145
  navigationKey(key3, { completing, options: options2 }) {
52924
53146
  const { p, value, commands, settings } = this;
52925
53147
  if (key3 === "\x1B[A" || key3 === "\x1B[B") {
@@ -52929,7 +53151,7 @@ ${kept}` : kept;
52929
53151
  this.draw();
52930
53152
  return true;
52931
53153
  }
52932
- if (!value) {
53154
+ if (!value || p.scrolledBack) {
52933
53155
  if (p.scrollTranscript(direction === -1 ? SWIPE_ROWS : -SWIPE_ROWS)) return true;
52934
53156
  if (direction === 1 && p.noteReadingDirection()) return true;
52935
53157
  }
@@ -52939,6 +53161,10 @@ ${kept}` : kept;
52939
53161
  this.draw();
52940
53162
  return true;
52941
53163
  }
53164
+ if (!value && !options2.length && (key3 === "" || key3 === "")) {
53165
+ p.scrollTranscript(key3 === "" ? Number.MAX_SAFE_INTEGER : -Number.MAX_SAFE_INTEGER);
53166
+ return true;
53167
+ }
52942
53168
  if (key3 === "" && !options2.length) {
52943
53169
  this.historyStep(-1);
52944
53170
  this.draw();
@@ -53107,7 +53333,7 @@ function composerLayout(value, cursor, available, maxRows = 6) {
53107
53333
  index = next;
53108
53334
  continue;
53109
53335
  }
53110
- const characterWidth = Math.max(1, terminalCellWidth(character));
53336
+ const characterWidth = character === " " ? TAB_WIDTH - column % TAB_WIDTH : Math.max(1, terminalCellWidth(character));
53111
53337
  if (column > 0 && column + characterWidth > width) {
53112
53338
  if (/\s/u.test(character)) {
53113
53339
  ranges.push({ start: rowStart, end: index });
@@ -53151,13 +53377,14 @@ function composerLayout(value, cursor, available, maxRows = 6) {
53151
53377
  break;
53152
53378
  }
53153
53379
  const start2 = Math.max(0, Math.min(position2.row - maxRows + 1, rows.length - maxRows));
53154
- const visible3 = rows.slice(start2, start2 + maxRows);
53380
+ const visible3 = rows.slice(start2, start2 + maxRows).map((row) => expandTabs(row));
53155
53381
  return { rows: visible3, cursorRow: position2.row - start2, cursorWidth: position2.column };
53156
53382
  }
53157
53383
  var init_composer_layout = __esm({
53158
53384
  "src/tui/render/composer-layout.ts"() {
53159
53385
  "use strict";
53160
53386
  init_width();
53387
+ init_text();
53161
53388
  }
53162
53389
  });
53163
53390
 
@@ -53635,7 +53862,7 @@ function createToolRows(p, builders) {
53635
53862
  lines: open13(["", ` ${row}`, ...live2])
53636
53863
  };
53637
53864
  };
53638
- const waitingOnApproval = (event) => event.id !== void 0 && (p.pendingApproval?.callId === event.id || p.approvalQueue.some((queued) => queued.callId === event.id));
53865
+ const waitingOnApproval = (event) => event.id !== void 0 && (p.pendingApproval?.callId === event.id || p.approvalQueue.some((queued2) => queued2.callId === event.id));
53639
53866
  const tagged = (lines4, group, item) => lines4.map((line3) => line3.trim() ? tagRow(line3, { group, item }) : line3);
53640
53867
  const summaryLine = (items, running4, plainOnly, open13 = false) => {
53641
53868
  const summary = groupSummary(items.map((item) => ({ id: item.key, event: item.event, ...item.thought ? { thought: item.thought } : {} })), running4, waitingOnApproval);
@@ -54287,6 +54514,7 @@ var init_prompter = __esm({
54287
54514
  init_modes();
54288
54515
  init_probe();
54289
54516
  init_state();
54517
+ init_history_dump();
54290
54518
  init_terminal_lifecycle();
54291
54519
  init_scroll_selection();
54292
54520
  init_mention();
@@ -54421,6 +54649,15 @@ var init_prompter = __esm({
54421
54649
  /** The width the transcript's rows were wrapped at. A resize to another
54422
54650
  * width wraps the whole conversation again (see rewrapTranscript). */
54423
54651
  transcriptColumns = output19.columns || 0;
54652
+ /** The first conversation row number (alternateTrimmed + index) not yet written into the normal screen; undefined: none of the current text has been. */
54653
+ dumpedThrough;
54654
+ /** Where the history dump stood when the transcript was rewritten for a new width: by message, which rewrapping keeps (row
54655
+ * numbers it does not). `into` is how many rows of that message were written. */
54656
+ dumpResume;
54657
+ /** Full-screen: the last size change was drawn whole the moment it arrived and no other came while the settle timer ran. */
54658
+ resizeSettled = false;
54659
+ /** A coalesced paint came due during a resize settle and was dropped; the settle repaints for it. */
54660
+ paintDropped = false;
54424
54661
  usageLabel;
54425
54662
  /** The owner of a conversation reached over SSH, shown in the status line. */
54426
54663
  remoteMachineName;
@@ -54552,6 +54789,9 @@ var init_prompter = __esm({
54552
54789
  /** Rows retired out of the viewport, kept so the conversation above the
54553
54790
  * live region is still there to scroll back to on the alternate screen. */
54554
54791
  alternateTranscript = [];
54792
+ /** Rows the cap on alternateTranscript has kept out of the view, and the line of the notice that says so (undefined: none). */
54793
+ capDropped = 0;
54794
+ capMarkerLine;
54555
54795
  /** Exactly the rows the last alternate-screen frame left on screen, so the
54556
54796
  * next one writes only what differs. */
54557
54797
  alternatePrevious = [];
@@ -54574,7 +54814,8 @@ var init_prompter = __esm({
54574
54814
  if (!output19.isTTY) {
54575
54815
  throw new Error("TerminalHarnessPrompter requires a TTY on stdout; construct it behind terminalUiSupported()");
54576
54816
  }
54577
- const inheritedScreen = process.env[REEXEC_TERMINAL_ENV] === "1";
54817
+ const handover = parseReexecHandover(process.env[REEXEC_TERMINAL_ENV]);
54818
+ const inheritedScreen = handover !== void 0;
54578
54819
  delete process.env[REEXEC_TERMINAL_ENV];
54579
54820
  terminalModes.uiStarted = true;
54580
54821
  setTerminalRawMode(true);
@@ -54583,13 +54824,10 @@ var init_prompter = __esm({
54583
54824
  output19.write(terminalPrepare());
54584
54825
  {
54585
54826
  logProcessWarnings();
54586
- if (inlineHistoryMode()) {
54587
- output19.write(`${CLEAR_SCREEN_AND_SCROLLBACK}\x1B[${Math.max(1, output19.rows || 24)};1H`);
54588
- } else {
54589
- if (!inheritedScreen) output19.write(ENTER_ALTERNATE_SCREEN);
54590
- terminalModes.alternateScreen = true;
54591
- }
54592
- output19.write(sessionModesOn(true));
54827
+ output19.write(reconcileScreen(handover, inlineHistoryMode(), output19.rows || 24).write);
54828
+ if (!inlineHistoryMode()) terminalModes.alternateScreen = true;
54829
+ output19.write(sessionModesOn());
54830
+ if (!inlineHistoryMode()) historyDump.source = () => this.takeHistoryDump();
54593
54831
  void probeTerminal();
54594
54832
  }
54595
54833
  if (inheritedScreen) terminalModes.titlePushed = true;
@@ -54860,6 +55098,7 @@ var init_prompter = __esm({
54860
55098
  rewrapIfWidthChanged,
54861
55099
  anchorBlock,
54862
55100
  clearTranscript,
55101
+ takeHistoryDump,
54863
55102
  activity,
54864
55103
  setPlan,
54865
55104
  settlePlan,
@@ -92592,10 +92831,10 @@ async function commandDuringTurn(sessionId, line3) {
92592
92831
  if (!session2) throw new Error(`AI session "${sessionId}" was not found`);
92593
92832
  const submission = { id: randomUUID42(), text: line3, submittedAt: (/* @__PURE__ */ new Date()).toISOString() };
92594
92833
  if (isShellCommandLine(line3)) {
92595
- const queued2 = { ...submission, kind: "command" };
92596
- enqueueSessionTurn(session2, queued2, queued2.submittedAt);
92834
+ const queued3 = { ...submission, kind: "command" };
92835
+ enqueueSessionTurn(session2, queued3, queued3.submittedAt);
92597
92836
  await writeState(state);
92598
- return { disposition: "command", submission: queued2, commandOutcome: "later" };
92837
+ return { disposition: "command", submission: queued3, commandOutcome: "later" };
92599
92838
  }
92600
92839
  const route = routeSlashInput(line3, slashRouteContextFor(
92601
92840
  session2,
@@ -92613,10 +92852,10 @@ async function commandDuringTurn(sessionId, line3) {
92613
92852
  return { disposition: "command", submission, commandOutcome: "applied" };
92614
92853
  }
92615
92854
  const isCommand = route.kind !== "prompt" && route.kind !== "native";
92616
- const queued = { ...submission, ...isCommand ? { kind: "command" } : {} };
92617
- enqueueSessionTurn(session2, queued, queued.submittedAt);
92855
+ const queued2 = { ...submission, ...isCommand ? { kind: "command" } : {} };
92856
+ enqueueSessionTurn(session2, queued2, queued2.submittedAt);
92618
92857
  await writeState(state);
92619
- return { disposition: isCommand ? "command" : "queued", submission: queued, ...isCommand ? { commandOutcome: "later" } : {} };
92858
+ return { disposition: isCommand ? "command" : "queued", submission: queued2, ...isCommand ? { commandOutcome: "later" } : {} };
92620
92859
  }
92621
92860
  var init_queue = __esm({
92622
92861
  "src/tui/slash/queue.ts"() {
@@ -94012,6 +94251,50 @@ var init_status = __esm({
94012
94251
  }
94013
94252
  });
94014
94253
 
94254
+ // src/runtime/event-loop-monitor.ts
94255
+ import { monitorEventLoopDelay } from "node:perf_hooks";
94256
+ function blockedLogger(write2, now = Date.now, thresholdMs = BLOCKED_THRESHOLD_MS, gapMs = BLOCKED_LOG_GAP_MS) {
94257
+ let lastWritten;
94258
+ let suppressed = 0;
94259
+ return (worstMs) => {
94260
+ if (worstMs <= thresholdMs) return;
94261
+ const at = now();
94262
+ if (lastWritten !== void 0 && at - lastWritten < gapMs) {
94263
+ suppressed += 1;
94264
+ return;
94265
+ }
94266
+ lastWritten = at;
94267
+ const skipped = suppressed;
94268
+ suppressed = 0;
94269
+ write2({ ms: Math.round(worstMs), suppressed: skipped });
94270
+ };
94271
+ }
94272
+ function startEventLoopMonitor() {
94273
+ const histogram = monitorEventLoopDelay({ resolution: 20 });
94274
+ histogram.enable();
94275
+ const note = blockedLogger(({ ms, suppressed }) => lifecycle("event-loop.blocked", { ms, ...suppressed ? { suppressed } : {} }));
94276
+ const timer = setInterval(() => {
94277
+ const worstMs = histogram.max / 1e6;
94278
+ histogram.reset();
94279
+ note(worstMs);
94280
+ }, SAMPLE_MS);
94281
+ timer.unref();
94282
+ return () => {
94283
+ clearInterval(timer);
94284
+ histogram.disable();
94285
+ };
94286
+ }
94287
+ var BLOCKED_THRESHOLD_MS, BLOCKED_LOG_GAP_MS, SAMPLE_MS;
94288
+ var init_event_loop_monitor = __esm({
94289
+ "src/runtime/event-loop-monitor.ts"() {
94290
+ "use strict";
94291
+ init_lifecycle_log();
94292
+ BLOCKED_THRESHOLD_MS = 100;
94293
+ BLOCKED_LOG_GAP_MS = 1e4;
94294
+ SAMPLE_MS = 1e3;
94295
+ }
94296
+ });
94297
+
94015
94298
  // src/session/state/sweep.ts
94016
94299
  import { stat as stat59, utimes as utimes4, writeFile as writeFile31 } from "node:fs/promises";
94017
94300
  import { join as join103 } from "node:path";
@@ -94300,9 +94583,9 @@ async function prepareTurn(targetId) {
94300
94583
  }
94301
94584
  async function afterTurnFailure(prompter, id, error, turn) {
94302
94585
  const cancelled = isTurnCancelled(error);
94303
- const queued = Boolean(turn.queuedTurnId && !cancelled);
94304
- if (queued) await releaseQueuedTurn(id, turn.queuedTurnId).catch(quiet("session/attach"));
94305
- const back = queued && turn.line ? [turn.line] : [];
94586
+ const queued2 = Boolean(turn.queuedTurnId && !cancelled);
94587
+ if (queued2) await releaseQueuedTurn(id, turn.queuedTurnId).catch(quiet("session/attach"));
94588
+ const back = queued2 && turn.line ? [turn.line] : [];
94306
94589
  const message2 = error instanceof Error ? error.message : String(error);
94307
94590
  if (cancelled || !prompter || !turn.line || !isUsageExhaustedMessage(message2)) return { cancelled, back };
94308
94591
  const next = await carryOnAfterExhaustion(prompter, id, turn.line, turn.guard, turn.sent ?? turn.line);
@@ -94580,7 +94863,7 @@ var init_credit_label = __esm({
94580
94863
  });
94581
94864
 
94582
94865
  // src/commands/ai/build-replace.ts
94583
- import { spawnSync as spawnSync3 } from "node:child_process";
94866
+ import { spawnSync as spawnSync2 } from "node:child_process";
94584
94867
  import { stdout } from "node:process";
94585
94868
  function relaunchArgv(entry2, sessionId) {
94586
94869
  return sessionId ? [entry2, "sessions", "resume", sessionId] : [entry2];
@@ -94596,26 +94879,38 @@ function replaceCliWithNewBuild(input11) {
94596
94879
  await input11.release();
94597
94880
  } catch {
94598
94881
  }
94882
+ const handOverTyped = () => {
94883
+ let text7 = "";
94884
+ try {
94885
+ text7 = input11.typed?.() ?? "";
94886
+ } catch {
94887
+ }
94888
+ if (text7) process.env[REEXEC_TYPED_ENV] = text7;
94889
+ else delete process.env[REEXEC_TYPED_ENV];
94890
+ };
94599
94891
  if (typeof process.execve === "function") {
94600
- await new Promise((resolve14) => stdout.write("", () => resolve14()));
94892
+ await new Promise((resolve14) => stdout.write(popReadModes(), () => resolve14()));
94601
94893
  await fileLocksIdle();
94894
+ handOverTyped();
94602
94895
  try {
94603
94896
  process.execve(
94604
94897
  process.execPath,
94605
94898
  [process.execPath, ...relaunchArgv(entry2, sessionId)],
94606
- { ...process.env, [REEXEC_TERMINAL_ENV]: "1" }
94899
+ { ...process.env, [REEXEC_TERMINAL_ENV]: reexecHandover() }
94607
94900
  );
94608
94901
  } catch {
94609
94902
  }
94610
94903
  }
94904
+ historyDump.suppressed = true;
94611
94905
  try {
94612
94906
  input11.closeUi();
94613
94907
  } catch {
94614
94908
  }
94615
94909
  await fileLocksIdle();
94910
+ handOverTyped();
94616
94911
  let status3 = 1;
94617
94912
  try {
94618
- const result = spawnSync3(process.execPath, relaunchArgv(entry2, sessionId), { stdio: "inherit" });
94913
+ const result = spawnSync2(process.execPath, relaunchArgv(entry2, sessionId), { stdio: "inherit" });
94619
94914
  status3 = result.status ?? 1;
94620
94915
  } finally {
94621
94916
  process.exit(status3);
@@ -94629,6 +94924,7 @@ var init_build_replace2 = __esm({
94629
94924
  "use strict";
94630
94925
  init_locks();
94631
94926
  init_restore();
94927
+ init_modes();
94632
94928
  init_ephemeral();
94633
94929
  }
94634
94930
  });
@@ -95184,11 +95480,15 @@ __export(connection_exports, {
95184
95480
  tapWindowMachine: () => tapWindowMachine
95185
95481
  });
95186
95482
  import { randomUUID as randomUUID47 } from "node:crypto";
95483
+ import { networkInterfaces as networkInterfaces2 } from "node:os";
95187
95484
  import { createInterface as createInterface4 } from "node:readline";
95188
95485
  function needsUpdate(ready, localCommit = localBuildCommit()) {
95189
95486
  if (ready.protocol !== void 0 && ready.protocol !== IDE_PROTOCOL.version) return true;
95190
95487
  return Boolean(ready.commit && localCommit && ready.commit !== localCommit);
95191
95488
  }
95489
+ function networkSignature() {
95490
+ return JSON.stringify(Object.values(networkInterfaces2()).flatMap((list2) => (list2 ?? []).filter((i) => !i.internal).map((i) => i.address)).sort());
95491
+ }
95192
95492
  function holdWindowMachines(use2 = {}, options2 = {}) {
95193
95493
  windowMachines ??= new RemoteMachines(options2, true);
95194
95494
  return windowMachines.hold(use2);
@@ -95212,7 +95512,7 @@ async function closeWindowMachines() {
95212
95512
  windowMachines = void 0;
95213
95513
  await machines?.close();
95214
95514
  }
95215
- var CHAT, READY_TIMEOUT_MS, REQUEST_TIMEOUT_MS3, STDERR_KEEP2, BACKOFF_MS, CACHE_WRITE_MS, RemoteLink, RemoteMachines, windowMachines;
95515
+ var CHAT, READY_TIMEOUT_MS, REQUEST_TIMEOUT_MS3, STDERR_KEEP2, BACKOFF_MS, NETWORK_POLL_MS, CACHE_WRITE_MS, RemoteLink, RemoteMachines, windowMachines;
95216
95516
  var init_connection = __esm({
95217
95517
  "src/remote/connection.ts"() {
95218
95518
  "use strict";
@@ -95229,7 +95529,8 @@ var init_connection = __esm({
95229
95529
  READY_TIMEOUT_MS = 3e4;
95230
95530
  REQUEST_TIMEOUT_MS3 = 6e4;
95231
95531
  STDERR_KEEP2 = 16e3;
95232
- BACKOFF_MS = [1e3, 2e3, 5e3, 1e4, 3e4];
95532
+ BACKOFF_MS = [1e3, 2e3, 5e3, 1e4, 3e4, 6e4, 12e4, 24e4, 48e4, 6e5];
95533
+ NETWORK_POLL_MS = 3e4;
95233
95534
  CACHE_WRITE_MS = 5e3;
95234
95535
  RemoteLink = class {
95235
95536
  constructor(machine, changed, options2 = {}) {
@@ -95286,6 +95587,7 @@ var init_connection = __esm({
95286
95587
  /** When the connection being made began: how long a host takes to say it is ready is the number that says the link is slow. */
95287
95588
  connectedAt = 0;
95288
95589
  connect() {
95590
+ this.stopNetworkWatch();
95289
95591
  const machine = this.view.machine;
95290
95592
  this.connectedAt = Date.now();
95291
95593
  lifecycle("remote.connect", { machine: machine.name, attempt: this.attempt });
@@ -95363,6 +95665,30 @@ ${error.message}`;
95363
95665
  this.connect();
95364
95666
  }, wait);
95365
95667
  this.retry.unref();
95668
+ if (wait >= NETWORK_POLL_MS * 2) {
95669
+ const signature2 = this.options.networkSignature ?? networkSignature;
95670
+ const before = signature2();
95671
+ this.netWatch = setInterval(() => {
95672
+ if (signature2() === before) return;
95673
+ this.stopNetworkWatch();
95674
+ clearTimeout(this.retry);
95675
+ this.retry = void 0;
95676
+ if (this.stopped || !this.wanted()) {
95677
+ this.parked = !this.stopped;
95678
+ return;
95679
+ }
95680
+ this.attempt = 0;
95681
+ lifecycle("remote.network-changed", { machine: this.view.machine.name });
95682
+ this.set({ state: "connecting", error: void 0 });
95683
+ this.connect();
95684
+ }, NETWORK_POLL_MS);
95685
+ this.netWatch.unref();
95686
+ }
95687
+ }
95688
+ netWatch;
95689
+ stopNetworkWatch() {
95690
+ if (this.netWatch) clearInterval(this.netWatch);
95691
+ this.netWatch = void 0;
95366
95692
  }
95367
95693
  /** A list shows the machine again: one offline is tried at once, not after
95368
95694
  * its pause (as a fresh connection would be); one connected is left as is. */
@@ -95610,6 +95936,7 @@ ${error.message}`;
95610
95936
  async stop() {
95611
95937
  this.stopped = true;
95612
95938
  clearTimeout(this.retry);
95939
+ this.stopNetworkWatch();
95613
95940
  clearTimeout(this.readyTimer);
95614
95941
  const child = this.child;
95615
95942
  this.child = void 0;
@@ -95820,6 +96147,8 @@ async function openWindow(config2, startId) {
95820
96147
  return conversationCommands(target, ref.paletteState);
95821
96148
  };
95822
96149
  const terminal = terminalUiSupported() ? new TerminalHarnessPrompter() : void 0;
96150
+ const handedTyped = adoptHandedOverTyped();
96151
+ if (terminal && handedTyped) terminal.restoreDraft(handedTyped);
95823
96152
  const rl = terminal ?? createInterface5({
95824
96153
  input: input10,
95825
96154
  output: output22,
@@ -95923,6 +96252,7 @@ function startBuildWatch(terminal, ref, refreshUsage, stopLockNotices) {
95923
96252
  sessionId,
95924
96253
  ...draft ? { draft } : {},
95925
96254
  closeUi: () => terminal.close(),
96255
+ typed: () => terminal.composer.text,
95926
96256
  release: async () => {
95927
96257
  await releaseWindow();
95928
96258
  await releaseConversationClaim(sessionId).catch(quiet("commands/ai/interactive/window"));
@@ -98384,7 +98714,7 @@ async function runRemoteChat(terminal, localId, first2, firstDraft, startBridge2
98384
98714
  commandsFor = key3;
98385
98715
  };
98386
98716
  const submissions = /* @__PURE__ */ new Map();
98387
- const queued = async (text7, windowId) => {
98717
+ const queued2 = async (text7, windowId) => {
98388
98718
  const id = windowId ?? randomUUID49();
98389
98719
  const submission = { id, text: text7, submittedAt: (/* @__PURE__ */ new Date()).toISOString() };
98390
98720
  const answered = new Promise((resolve14, reject) => {
@@ -98407,7 +98737,7 @@ async function runRemoteChat(terminal, localId, first2, firstDraft, startBridge2
98407
98737
  };
98408
98738
  const windowCommandOrQueued = async (text7, windowId) => {
98409
98739
  const own = resolveSlashCommand(parseSlashInput(text7)?.head ?? "")?.name;
98410
- if (own !== "restart" && own !== "send") return queued(text7, windowId);
98740
+ if (own !== "restart" && own !== "send") return queued2(text7, windowId);
98411
98741
  const submission = { id: windowId ?? randomUUID49(), text: text7, submittedAt: (/* @__PURE__ */ new Date()).toISOString() };
98412
98742
  if (own === "restart") {
98413
98743
  const leaving = replaceWindowBuild();
@@ -98453,7 +98783,7 @@ async function runRemoteChat(terminal, localId, first2, firstDraft, startBridge2
98453
98783
  terminal.startWaiting(
98454
98784
  label3,
98455
98785
  (restoreDraft) => bridge.post({ type: "cancel", restoreDraft }),
98456
- queued,
98786
+ queued2,
98457
98787
  windowCommandOrQueued,
98458
98788
  leave,
98459
98789
  // Esc on a waiting message takes that message back, and does not stop the turn; "Enter again" offers it to the running turn now.
@@ -100030,8 +100360,8 @@ var init_loop = __esm({
100030
100360
  let line3;
100031
100361
  let queuedTurnId;
100032
100362
  let fromQueuedCommand = false;
100033
- let queued = latest3.queuedTurns?.[0];
100034
- if (terminal?.takeStopped() && !running4 && !this.openBoard && queued && queued.kind !== "command" && queued.kind !== "notification") {
100363
+ let queued2 = latest3.queuedTurns?.[0];
100364
+ if (terminal?.takeStopped() && !running4 && !this.openBoard && queued2 && queued2.kind !== "command" && queued2.kind !== "notification") {
100035
100365
  const back = [];
100036
100366
  for (const entry2 of [...latest3.queuedTurns ?? []]) {
100037
100367
  if (entry2.kind === "command" || entry2.kind === "notification") continue;
@@ -100041,7 +100371,7 @@ var init_loop = __esm({
100041
100371
  await writeState(latestState);
100042
100372
  terminal.restoreDraft([terminal.queuedDraft, ...back].filter(Boolean).join("\n"));
100043
100373
  }
100044
- queued = latest3.queuedTurns?.[0];
100374
+ queued2 = latest3.queuedTurns?.[0];
100045
100375
  }
100046
100376
  if (this.openBoard) {
100047
100377
  this.openBoard = false;
@@ -100212,6 +100542,7 @@ async function aiSessionInteractive(config2, id) {
100212
100542
  process.on("SIGINT", ignoreInterrupt);
100213
100543
  setLifecycleRole("window", id);
100214
100544
  lifecycle("window.open", { cols: process.stdout.columns, rows: process.stdout.rows, tty: Boolean(process.stdin.isTTY) });
100545
+ const stopMonitor = startEventLoopMonitor();
100215
100546
  try {
100216
100547
  await aiSessionInteractiveInner(config2, id);
100217
100548
  lifecycle("window.exit", { how: "left" });
@@ -100219,6 +100550,7 @@ async function aiSessionInteractive(config2, id) {
100219
100550
  lifecycle("window.exit", { how: "error", message: error instanceof Error ? error.message.slice(0, 300) : String(error) });
100220
100551
  throw error;
100221
100552
  } finally {
100553
+ stopMonitor();
100222
100554
  process.off("SIGINT", ignoreInterrupt);
100223
100555
  }
100224
100556
  }
@@ -100232,6 +100564,7 @@ var init_interactive = __esm({
100232
100564
  "src/commands/ai/interactive.ts"() {
100233
100565
  "use strict";
100234
100566
  init_lifecycle_log();
100567
+ init_event_loop_monitor();
100235
100568
  init_ephemeral();
100236
100569
  init_attach();
100237
100570
  init_window();
@@ -105431,13 +105764,13 @@ var init_bridge_turns = __esm({
105431
105764
  const session2 = state.sessions.find((item) => item.id === this.host.sessionId);
105432
105765
  const next = session2 ? queuedNext(session2, { stopped: this.host.link.stopped, ...previous ? { justRan: previous } : {} }) : void 0;
105433
105766
  if (!session2 || !next) return;
105434
- const queued = next.entry;
105435
- previous = queued.id;
105767
+ const queued2 = next.entry;
105768
+ previous = queued2.id;
105436
105769
  if (next.kind === "command") {
105437
- if (consumeSessionTurn(session2, queued.id)) await writeState(state);
105438
- await this.host.execute(queued.text, { fromQueuedCommand: true });
105770
+ if (consumeSessionTurn(session2, queued2.id)) await writeState(state);
105771
+ await this.host.execute(queued2.text, { fromQueuedCommand: true });
105439
105772
  } else {
105440
- await this.host.execute(queued.text, { queuedTurnId: queued.id });
105773
+ await this.host.execute(queued2.text, { queuedTurnId: queued2.id });
105441
105774
  }
105442
105775
  }
105443
105776
  }
@@ -105563,14 +105896,14 @@ var init_bridge_turns = __esm({
105563
105896
 
105564
105897
  // src/ide/bridge-choose-conversation.ts
105565
105898
  async function chooseConversation(cx, choice) {
105566
- const { host, queued } = cx;
105899
+ const { host, queued: queued2 } = cx;
105567
105900
  switch (choice.kind) {
105568
105901
  case "conversation": {
105569
105902
  const current5 = choice.sessionId === host.sessionId;
105570
105903
  if (current5 && host.link.workerTurnRunning && choice.action === "delete") {
105571
105904
  throw new Error("A turn is running in this conversation: stop it first.");
105572
105905
  }
105573
- queued(async () => {
105906
+ queued2(async () => {
105574
105907
  const replacement = current5 && choice.action === "delete" ? await newConversation(choice.sessionId) : void 0;
105575
105908
  if (choice.action === "rename") {
105576
105909
  const name = choice.name?.trim();
@@ -105597,10 +105930,10 @@ var init_bridge_choose_conversation = __esm({
105597
105930
 
105598
105931
  // src/ide/bridge-choose-provider.ts
105599
105932
  async function chooseProvider(cx, choice) {
105600
- const { host, done, queued } = cx;
105933
+ const { host, done, queued: queued2 } = cx;
105601
105934
  switch (choice.kind) {
105602
105935
  case "provider": {
105603
- queued(async () => {
105936
+ queued2(async () => {
105604
105937
  const id = host.requireSession();
105605
105938
  const moved = await selectProviderConversation(host.config, host.prompter, id, providerConversationKey(choice.provider), { offerLocal: true });
105606
105939
  if (choice.model) {
@@ -105617,7 +105950,7 @@ async function chooseProvider(cx, choice) {
105617
105950
  return true;
105618
105951
  }
105619
105952
  case "hosted":
105620
- queued(async () => {
105953
+ queued2(async () => {
105621
105954
  const selection = await hostedAdapter(choice.row.target).start(choice.row);
105622
105955
  const id = host.requireSession();
105623
105956
  const moved = selection.route === "gateway" ? await selectProviderConversation(host.config, host.prompter, id, providerConversationKey(GATEWAY_ID)) : id;
@@ -105631,7 +105964,7 @@ async function chooseProvider(cx, choice) {
105631
105964
  });
105632
105965
  return true;
105633
105966
  case "add-account":
105634
- queued(async () => {
105967
+ queued2(async () => {
105635
105968
  const harness = localHarnessForCommand(choice.provider);
105636
105969
  if (!harness) throw new Error(`unknown provider "${choice.provider}"`);
105637
105970
  const added2 = await addAccountForHarness(host.prompter, harness);
@@ -105644,7 +105977,7 @@ async function chooseProvider(cx, choice) {
105644
105977
  });
105645
105978
  return true;
105646
105979
  case "account-action":
105647
- queued(async () => {
105980
+ queued2(async () => {
105648
105981
  await manageAccountAction(host.prompter, choice.accountId, choice.action);
105649
105982
  await host.emitSession().catch(quiet("ide/bridge-choose-provider"));
105650
105983
  });
@@ -105768,7 +106101,7 @@ async function choose(host, requestId, choice) {
105768
106101
  });
105769
106102
  await host.emitSession();
105770
106103
  };
105771
- const queued = (job) => {
106104
+ const queued2 = (job) => {
105772
106105
  host.enqueue(async () => {
105773
106106
  try {
105774
106107
  done(await quietly(job));
@@ -105777,7 +106110,7 @@ async function choose(host, requestId, choice) {
105777
106110
  }
105778
106111
  });
105779
106112
  };
105780
- const cx = { host, done, setting: setting2, queued };
106113
+ const cx = { host, done, setting: setting2, queued: queued2 };
105781
106114
  try {
105782
106115
  const routed = await routedChoice(host, choice);
105783
106116
  if (await chooseSetting(cx, routed)) return;
@@ -107630,7 +107963,7 @@ async function exploreForKeys(deps, start2, options2 = {}) {
107630
107963
  const visited = [...options2.seen ?? []];
107631
107964
  const menus = [...options2.seenMenus ?? []];
107632
107965
  const tried = /* @__PURE__ */ new Set();
107633
- const queued = /* @__PURE__ */ new Set();
107966
+ const queued2 = /* @__PURE__ */ new Set();
107634
107967
  const frontier = [];
107635
107968
  let pages = 0;
107636
107969
  let current5 = start2;
@@ -107645,8 +107978,8 @@ async function exploreForKeys(deps, start2, options2 = {}) {
107645
107978
  const enqueue2 = (c, from, rank, via) => {
107646
107979
  const href = httpsHref(c);
107647
107980
  const key3 = href ? pathOf(href) : `${via ?? ""}>${c.name}`;
107648
- if (queued.has(key3) || href && visited.includes(pathOf(href))) return;
107649
- queued.add(key3);
107981
+ if (queued2.has(key3) || href && visited.includes(pathOf(href))) return;
107982
+ queued2.add(key3);
107650
107983
  frontier.push({ name: c.name, ...href ? { href } : {}, from, ...via ? { via } : {}, rank });
107651
107984
  frontier.sort((a2, b) => a2.rank - b.rank);
107652
107985
  };
@@ -115825,10 +116158,11 @@ function handleCommandError(error) {
115825
116158
  }
115826
116159
  var TERMINAL_ENVIRONMENT_HELP = `
115827
116160
  Terminal environment:
115828
- CLIKCODE_INLINE=1|0 Force inline-history mode (scrollback, no alternate screen or mouse) on or off.
115829
- Unset: inline in GNU screen, in tmux unless its "mouse" option is on,
115830
- TERM=dumb|linux, and over ssh from a terminal not known to be a good one;
115831
- full-screen in iTerm, Terminal, WezTerm, ghostty, kitty, VS Code and Alacritty.
116161
+ CLIKCODE_INLINE=1 Inline-history mode: the conversation is printed into the terminal's own scrollback and only
116162
+ the composer is redrawn. Unset: full-screen everywhere (the alternate screen; the conversation
116163
+ is written into your scrollback when ClikCode ends or is suspended).
116164
+ CLIKCODE_MOUSE=1 Ask the terminal for mouse reporting (wheel and its own selection). Unset: none, so the
116165
+ terminal's selection and copy work; PageUp, PageDown, Home, End and the arrows scroll.
115832
116166
  CLIKCODE_ASCII=1|0 Force ASCII rules, box drawing and spinner on or off. Unset: on when the locale
115833
116167
  (LC_ALL, LC_CTYPE, LANG) is not UTF-8 or TERM=linux.
115834
116168
  CLIKCODE_TUI=classic Line-oriented output instead of the live terminal UI.