@denizokcu/haze 1.2.0 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (179) hide show
  1. package/CHANGELOG.md +86 -1
  2. package/README.md +23 -10
  3. package/SECURITY.md +1 -1
  4. package/bin/haze.js +27 -7
  5. package/dist/buildInfo.json +3 -3
  6. package/dist/cli/chat/BusyBar.d.ts +7 -0
  7. package/dist/cli/chat/BusyBar.js +8 -0
  8. package/dist/cli/chat/DynamicFrame.d.ts +37 -0
  9. package/dist/cli/chat/DynamicFrame.js +43 -0
  10. package/dist/cli/chat/busyIndicator.d.ts +3 -1
  11. package/dist/cli/chat/busyIndicator.js +11 -9
  12. package/dist/cli/chat/chatMetrics.d.ts +1 -1
  13. package/dist/cli/chat/chatMetrics.js +3 -3
  14. package/dist/cli/chat/inputSuggestions.js +4 -0
  15. package/dist/cli/chat/liveMessages.d.ts +36 -0
  16. package/dist/cli/chat/liveMessages.js +64 -0
  17. package/dist/cli/chat/liveRegion.js +1 -1
  18. package/dist/cli/chat/messages.js +27 -16
  19. package/dist/cli/chat/sessionLifecycle.d.ts +5 -2
  20. package/dist/cli/chat/sessionLifecycle.js +36 -4
  21. package/dist/cli/chat/sessionRecorder.d.ts +2 -1
  22. package/dist/cli/chat/sessionRecorder.js +8 -0
  23. package/dist/cli/chat/shutdown.d.ts +27 -0
  24. package/dist/cli/chat/shutdown.js +79 -0
  25. package/dist/cli/chat/terminalControl.d.ts +45 -0
  26. package/dist/cli/chat/terminalControl.js +107 -0
  27. package/dist/cli/chat/tips.js +1 -0
  28. package/dist/cli/chat/userInput.d.ts +43 -0
  29. package/dist/cli/chat/userInput.js +63 -0
  30. package/dist/cli/chat/wizard/sessionThemeHandlers.d.ts +1 -1
  31. package/dist/cli/chat/wizard/sessionThemeHandlers.js +24 -1
  32. package/dist/cli/chat/wizard/types.d.ts +8 -1
  33. package/dist/cli/chat/wizardDispatch.js +1 -1
  34. package/dist/cli/commands/chat.js +277 -193
  35. package/dist/cli/commands/commandHelp.js +6 -0
  36. package/dist/cli/commands/commands.d.ts +8 -0
  37. package/dist/cli/commands/commands.js +13 -0
  38. package/dist/cli/commands/formatters.d.ts +1 -1
  39. package/dist/cli/commands/formatters.js +25 -3
  40. package/dist/cli/commands/logsCommand.js +21 -2
  41. package/dist/cli/commands/ndjsonSink.d.ts +12 -0
  42. package/dist/cli/commands/ndjsonSink.js +29 -0
  43. package/dist/cli/commands/reasoningCommand.d.ts +44 -0
  44. package/dist/cli/commands/reasoningCommand.js +79 -0
  45. package/dist/cli/commands/runCommand.d.ts +14 -0
  46. package/dist/cli/commands/runCommand.js +56 -22
  47. package/dist/cli/commands/settingsSummary.js +2 -0
  48. package/dist/cli/commands/streaming/agentAttempt.d.ts +3 -0
  49. package/dist/cli/commands/streaming/agentAttempt.js +2 -2
  50. package/dist/cli/commands/streaming/assistantSegments.d.ts +0 -7
  51. package/dist/cli/commands/streaming/assistantSegments.js +1 -1
  52. package/dist/cli/commands/streaming/attemptLifecycle.js +13 -9
  53. package/dist/cli/commands/streaming/attemptOutcome.d.ts +2 -0
  54. package/dist/cli/commands/streaming/attemptOutcome.js +24 -9
  55. package/dist/cli/commands/streaming/attemptSetup.d.ts +4 -0
  56. package/dist/cli/commands/streaming/attemptSetup.js +21 -7
  57. package/dist/cli/commands/streaming/goalCheckpoint.d.ts +14 -1
  58. package/dist/cli/commands/streaming/goalCheckpoint.js +4 -2
  59. package/dist/cli/commands/streaming/goalSupervisor.d.ts +9 -0
  60. package/dist/cli/commands/streaming/goalSupervisor.js +51 -10
  61. package/dist/cli/commands/streaming/prepareStep.d.ts +0 -3
  62. package/dist/cli/commands/streaming/prepareStep.js +14 -5
  63. package/dist/cli/commands/streaming/streamLoop.d.ts +5 -0
  64. package/dist/cli/commands/streaming/streamLoop.js +3 -0
  65. package/dist/cli/commands/streaming/toolPartHandlers.js +6 -0
  66. package/dist/cli/commands/streaming.d.ts +8 -3
  67. package/dist/cli/commands/streaming.js +46 -21
  68. package/dist/cli/commands/wizardFlow.d.ts +10 -0
  69. package/dist/cli/commands/wizardFlow.js +34 -5
  70. package/dist/cli/index.js +22 -2
  71. package/dist/config/contextFiles.d.ts +9 -0
  72. package/dist/config/contextFiles.js +21 -1
  73. package/dist/config/modelCatalog.d.ts +3 -0
  74. package/dist/config/modelCatalog.js +29 -0
  75. package/dist/config/modelDiscovery.js +68 -5
  76. package/dist/config/providerPresets.d.ts +1 -1
  77. package/dist/config/providerPresets.js +42 -3
  78. package/dist/config/settings.d.ts +14 -6
  79. package/dist/config/settings.js +16 -1
  80. package/dist/core/agent/budgets.d.ts +13 -17
  81. package/dist/core/agent/budgets.js +15 -19
  82. package/dist/core/agent/completionController.d.ts +14 -2
  83. package/dist/core/agent/completionController.js +48 -3
  84. package/dist/core/agent/events.d.ts +2 -1
  85. package/dist/core/agent/goalPolicy.d.ts +17 -0
  86. package/dist/core/agent/goalPolicy.js +53 -6
  87. package/dist/core/agent/projectPreflight.d.ts +2 -0
  88. package/dist/core/agent/projectPreflight.js +56 -0
  89. package/dist/core/agent/reasoningPolicy.d.ts +76 -10
  90. package/dist/core/agent/reasoningPolicy.js +72 -9
  91. package/dist/core/agent/toolCapabilities.d.ts +3 -3
  92. package/dist/core/agent/toolCapabilities.js +31 -7
  93. package/dist/core/agent/workState.d.ts +14 -4
  94. package/dist/core/agent/workState.js +229 -34
  95. package/dist/core/deadline.js +22 -24
  96. package/dist/core/providerContracts.d.ts +29 -0
  97. package/dist/core/providerContracts.js +1 -0
  98. package/dist/core/safety/secretPaths.js +10 -7
  99. package/dist/core/safety/shellClassifier.d.ts +2 -0
  100. package/dist/core/safety/shellClassifier.js +9 -1
  101. package/dist/core/session/sessionReport.d.ts +33 -0
  102. package/dist/core/session/sessionReport.js +121 -0
  103. package/dist/core/session/sessionSlimming.d.ts +2 -0
  104. package/dist/core/session/sessionSlimming.js +59 -4
  105. package/dist/core/session/sessionStore.d.ts +16 -8
  106. package/dist/core/session/sessionStore.js +71 -34
  107. package/dist/core/shellOutput/reducers/git.js +7 -2
  108. package/dist/core/shellOutput/reducers/validation.d.ts +1 -1
  109. package/dist/core/shellOutput/reducers/validation.js +14 -1
  110. package/dist/core/shellOutput/registry.js +3 -2
  111. package/dist/core/subagent/contracts.d.ts +3 -18
  112. package/dist/core/subagent/executionProfiles.js +4 -4
  113. package/dist/core/tasks/taskStorage.js +8 -1
  114. package/dist/core/validation/outputParser.d.ts +6 -1
  115. package/dist/core/validation/outputParser.js +30 -2
  116. package/dist/llm/client.d.ts +6 -3
  117. package/dist/llm/client.js +28 -11
  118. package/dist/llm/hazeTools.d.ts +9161 -7135
  119. package/dist/llm/hazeTools.js +6 -462
  120. package/dist/llm/lsp/client.d.ts +7 -1
  121. package/dist/llm/lsp/client.js +58 -9
  122. package/dist/llm/lsp/pool.d.ts +11 -0
  123. package/dist/llm/lsp/pool.js +61 -4
  124. package/dist/llm/lsp/protocol.d.ts +6 -23
  125. package/dist/llm/lsp/requests.d.ts +54 -60
  126. package/dist/llm/lsp/requests.js +152 -28
  127. package/dist/llm/lsp/symbols.d.ts +16 -0
  128. package/dist/llm/lsp/symbols.js +70 -0
  129. package/dist/llm/lsp/workspaceEdit.d.ts +43 -0
  130. package/dist/llm/lsp/workspaceEdit.js +117 -0
  131. package/dist/llm/lspTools.d.ts +7518 -2859
  132. package/dist/llm/lspTools.js +195 -110
  133. package/dist/llm/mcp.js +3 -0
  134. package/dist/llm/requestContext.d.ts +4 -3
  135. package/dist/llm/requestContext.js +9 -5
  136. package/dist/{core/subagent → llm}/subagentRunner.d.ts +13 -9
  137. package/dist/{core/subagent → llm}/subagentRunner.js +54 -49
  138. package/dist/llm/systemPrompt.d.ts +11 -1
  139. package/dist/llm/systemPrompt.js +4 -13
  140. package/dist/llm/tools/fetchTool.d.ts +34 -30
  141. package/dist/llm/tools/fileTools.d.ts +7768 -0
  142. package/dist/llm/tools/fileTools.js +510 -0
  143. package/dist/llm/tools/processTool.d.ts +34 -30
  144. package/dist/llm/tools/replaceInFiles.d.ts +105 -0
  145. package/dist/llm/tools/replaceInFiles.js +131 -0
  146. package/dist/llm/tools/shellTool.d.ts +34 -30
  147. package/dist/llm/tools/shellTool.js +8 -4
  148. package/dist/llm/tools/storedOutputTool.d.ts +4 -0
  149. package/dist/llm/tools/taskTool.d.ts +4 -0
  150. package/dist/llm/tools/toolContext.d.ts +3 -29
  151. package/dist/llm/tools/toolContext.js +56 -53
  152. package/dist/llm/tools/toolContextState.d.ts +40 -0
  153. package/dist/llm/tools/toolContextState.js +34 -0
  154. package/dist/llm/workerContext.d.ts +7 -0
  155. package/dist/llm/workerContext.js +18 -1
  156. package/dist/skills/SkillLoader.js +30 -4
  157. package/dist/skills/SkillRegistry.js +3 -3
  158. package/dist/skills/builder/SkillBuilder.js +3 -3
  159. package/dist/skills/confinement.d.ts +7 -0
  160. package/dist/skills/confinement.js +15 -0
  161. package/dist/ui/codeHighlight.js +4 -4
  162. package/dist/ui/components/MarkdownText.js +7 -8
  163. package/dist/ui/components/NativeIndicators.d.ts +15 -0
  164. package/dist/ui/components/NativeIndicators.js +32 -0
  165. package/dist/ui/components/StreamingMarkdownText.d.ts +9 -0
  166. package/dist/ui/components/StreamingMarkdownText.js +38 -0
  167. package/dist/ui/components/TextInput.d.ts +7 -2
  168. package/dist/ui/components/TextInput.js +103 -46
  169. package/dist/ui/components/WizardChoices.d.ts +18 -0
  170. package/dist/ui/components/WizardChoices.js +32 -0
  171. package/dist/ui/components/useInputSuggestions.js +18 -6
  172. package/dist/ui/inputBuffer.js +12 -6
  173. package/dist/ui/textGeometry.d.ts +14 -0
  174. package/dist/ui/textGeometry.js +31 -0
  175. package/dist/utils/buildInfo.js +29 -8
  176. package/dist/utils/fs.js +5 -1
  177. package/package.json +23 -22
  178. /package/dist/cli/{contextReport.d.ts → contextReportCli.d.ts} +0 -0
  179. /package/dist/cli/{contextReport.js → contextReportCli.js} +0 -0
@@ -0,0 +1,32 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { Box, Text, useAnimation, useIsScreenReaderEnabled } from 'ink';
3
+ import { StatusMessage, ThemeProvider, defaultTheme, extendTheme } from '@inkjs/ui';
4
+ import { theme } from '../theme.js';
5
+ // Matches cli-spinners' `dots` (the @inkjs/ui Spinner type haze used), so the
6
+ // visual cadence is unchanged after moving to Ink's shared animation timer.
7
+ const SPINNER_FRAMES = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
8
+ const SPINNER_INTERVAL_MS = 80;
9
+ /** Map library indicators to the current palette, never its default colors. */
10
+ export function indicatorTheme(palette) {
11
+ const colors = { success: palette.success, error: palette.danger, warning: palette.warning, info: palette.info };
12
+ return extendTheme(defaultTheme, { components: {
13
+ StatusMessage: { styles: {
14
+ container: () => ({ gap: 1, flexShrink: 0, width: '100%', overflow: 'hidden' }),
15
+ icon: ({ variant }) => ({ color: colors[variant] }),
16
+ message: () => ({ color: palette.foreground, wrap: 'truncate-end' }),
17
+ } },
18
+ } });
19
+ }
20
+ /** A layout element: render beside Text, not nested inside it. */
21
+ export function ActivitySpinner({ color = theme.command }) {
22
+ const screenReader = useIsScreenReaderEnabled();
23
+ // Ink 8's shared animation timer: every animated component consolidates
24
+ // into one render cycle (throttled by maxFps) instead of per-spinner timers.
25
+ const { frame } = useAnimation({ interval: SPINNER_INTERVAL_MS });
26
+ const glyph = SPINNER_FRAMES[frame % SPINNER_FRAMES.length];
27
+ // Screen readers announce frame churn as noise; hold a static marker.
28
+ return _jsx(Box, { flexShrink: 0, children: _jsx(Text, { color: color, children: screenReader ? '·' : glyph }) });
29
+ }
30
+ export function StatusNotice({ variant, children }) {
31
+ return _jsx(ThemeProvider, { theme: indicatorTheme(theme), children: _jsx(StatusMessage, { variant: variant, children: children }) });
32
+ }
@@ -0,0 +1,9 @@
1
+ import React from 'react';
2
+ /** Parse the whole active block before splitting its formatted terminal output into rows. */
3
+ export declare function renderMarkdownRows(content: string, width: number): string[];
4
+ /** The active block remains replaceable; only settled roots belong in Static. */
5
+ export declare const StreamingMarkdownText: React.MemoExoticComponent<({ content, width, maxVisibleLines }: {
6
+ content: string;
7
+ width: number;
8
+ maxVisibleLines?: number;
9
+ }) => React.JSX.Element | null>;
@@ -0,0 +1,38 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import React, { useEffect, useState } from 'react';
3
+ import { Box, Text, renderToString } from 'ink';
4
+ import { MarkdownText } from './MarkdownText.js';
5
+ import { theme } from '../theme.js';
6
+ /** Parse the whole active block before splitting its formatted terminal output into rows. */
7
+ export function renderMarkdownRows(content, width) {
8
+ if (!content)
9
+ return [];
10
+ const output = renderToString(_jsx(MarkdownText, { content: content, width: width }), { columns: Math.max(1, width) });
11
+ // Block margins belong to the settled transcript, not the bottom of a live
12
+ // preview. Keep internal blank rows, but do not let a trailing margin hide
13
+ // the newest content in a small viewport.
14
+ return output.replace(/\n[\s]*$/, '').split('\n');
15
+ }
16
+ /** The active block remains replaceable; only settled roots belong in Static. */
17
+ export const StreamingMarkdownText = React.memo(function StreamingMarkdownText({ content, width, maxVisibleLines }) {
18
+ const [rendered, setRendered] = useState({ content: '', width, rows: [] });
19
+ // Ink's synchronous offscreen renderer must run outside React's render and
20
+ // commit phases. The microtask also lets superseded deltas cancel their work.
21
+ useEffect(() => {
22
+ let cancelled = false;
23
+ queueMicrotask(() => {
24
+ if (!cancelled)
25
+ setRendered({ content, width, rows: renderMarkdownRows(content, width) });
26
+ });
27
+ return () => { cancelled = true; };
28
+ }, [content, width]);
29
+ // Never replay a previous root after it enters Static, or show stale, wider
30
+ // rows during a terminal resize. Append-only deltas can retain their preview.
31
+ const rows = rendered.width === width && content.startsWith(rendered.content) ? rendered.rows : [];
32
+ const budget = maxVisibleLines == null ? rows.length : Math.max(0, Math.floor(maxVisibleLines));
33
+ if (budget === 0)
34
+ return null;
35
+ const hidden = rows.length > budget ? rows.length - Math.max(0, budget - 1) : 0;
36
+ const visible = hidden ? rows.slice(hidden) : rows;
37
+ return _jsxs(Box, { flexDirection: "column", flexShrink: 0, children: [hidden > 0 ? _jsx(Text, { color: theme.muted, wrap: "truncate-end", children: `⋯ +${hidden} line${hidden === 1 ? '' : 's'} above` }) : null, visible.map((row, index) => _jsx(Text, { wrap: "truncate-end", children: row || ' ' }, hidden + index))] });
38
+ });
@@ -6,7 +6,6 @@ type TextInputKey = {
6
6
  meta?: boolean;
7
7
  };
8
8
  export declare function shouldInsertNewline(input: string, key: TextInputKey): boolean;
9
- export declare function isKittyQueryResponseInput(input: string): boolean;
10
9
  /**
11
10
  * Ctrl+C terminate check. Legacy terminals deliver the raw \x03 byte (Ink
12
11
  * parses it to `c` + ctrl); with the kitty keyboard protocol enabled the
@@ -22,7 +21,7 @@ export type TextInputSuggestion = {
22
21
  };
23
22
  /** Cursor-aware path completer for `@token` mentions; receives the token verbatim. */
24
23
  export type MentionSuggestionsProvider = (token: string) => Promise<TextInputSuggestion[]> | TextInputSuggestion[];
25
- export declare function TextInput({ placeholder, disabled, mask, historyItems, recordHistory, suggestions, suggestionMode, submitOnEmpty, width, getMentionSuggestions, onHistoryAdd, onCancel, onEscape, onToggleTasks, onResumeKey, onInterrupt, onSubmit }: {
24
+ export declare function TextInput({ placeholder, disabled, mask, historyItems, recordHistory, suggestions, suggestionMode, submitOnEmpty, width, inputRows, suggestionRows, onRowsChange, getMentionSuggestions, onHistoryAdd, onCancel, onEscape, onToggleTasks, onResumeKey, onInterrupt, onSubmit }: {
26
25
  placeholder?: string;
27
26
  disabled?: boolean;
28
27
  mask?: boolean;
@@ -32,6 +31,12 @@ export declare function TextInput({ placeholder, disabled, mask, historyItems, r
32
31
  suggestionMode?: 'slash' | 'always';
33
32
  submitOnEmpty?: boolean;
34
33
  width?: number;
34
+ inputRows?: number;
35
+ suggestionRows?: number;
36
+ onRowsChange?: (demand: {
37
+ input: number;
38
+ suggestions: number;
39
+ }) => void;
35
40
  getMentionSuggestions?: MentionSuggestionsProvider;
36
41
  onHistoryAdd?: (value: string) => void;
37
42
  onCancel?: () => void;
@@ -1,12 +1,14 @@
1
- import { jsxs as _jsxs, jsx as _jsx, Fragment as _Fragment } from "react/jsx-runtime";
1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
2
  import { useEffect, useRef, useState } from 'react';
3
- import { Box, Text, useInput } from 'ink';
3
+ import { Box, Text, measureElement, useCursor, useInput, useIsScreenReaderEnabled, usePaste } from 'ink';
4
+ import { cellWidth, graphemes, nextBoundary, offsetAtColumn, previousBoundary, safeInputDisplay } from '../textGeometry.js';
4
5
  import { theme } from '../theme.js';
5
6
  import { compactPasteBlocksForDisplay, cursorPosition, displayCursorForValueCursor, lineCount, normalizeLineEndings, updatePasteBlocksForReplacement, valueCursorForDisplayCursor, wrapDisplayValue, } from '../inputBuffer.js';
6
7
  import { useInputSuggestions } from './useInputSuggestions.js';
8
+ import { WizardChoices } from './WizardChoices.js';
7
9
  const COMPACT_PASTE_MIN_LINES = 4;
8
10
  // Enhanced-keyboard encodings of Enter with modifiers that some terminals emit
9
- // verbatim (kitty/CSI-u `u` form and xterm modifyOtherKeys `~` form). Ink 7's
11
+ // verbatim (kitty/CSI-u `u` form and xterm modifyOtherKeys `~` form). Ink's
10
12
  // keypress parser already resolves the CSI-u variants to `key.return` plus the
11
13
  // modifier flags before TextInput sees them; these entries cover pipelines that
12
14
  // deliver the raw sequence through `input`.
@@ -21,20 +23,6 @@ export function shouldInsertNewline(input, key) {
21
23
  || input === '\n'
22
24
  || NEWLINE_ESCAPE_INPUTS.has(input);
23
25
  }
24
- // Ink's kitty-keyboard auto-detection (enabled via the chat render option)
25
- // queries the terminal with CSI ? u. The terminal's CSI ? <flags> u response
26
- // can race Ink's detection listener and leak through the normal input pipeline
27
- // as literal text (Ink's keypress handling strips the leading ESC), which would
28
- // type e.g. `[?0u` into an otherwise empty prompt at startup. Drop probe
29
- // responses instead of inserting them.
30
- const KITTY_QUERY_RESPONSE_INPUT = /^\[\?\d+(?:;\d+)*u$/;
31
- export function isKittyQueryResponseInput(input) {
32
- // Ink's keypress handling strips one leading ESC from unresolved sequences,
33
- // so the probe response normally arrives as `[?0u`; tolerate the raw
34
- // ESC-prefixed form as well.
35
- const stripped = input.startsWith('\u001B') ? input.slice(1) : input;
36
- return KITTY_QUERY_RESPONSE_INPUT.test(stripped);
37
- }
38
26
  /**
39
27
  * Ctrl+C terminate check. Legacy terminals deliver the raw \x03 byte (Ink
40
28
  * parses it to `c` + ctrl); with the kitty keyboard protocol enabled the
@@ -45,15 +33,40 @@ export function isKittyQueryResponseInput(input) {
45
33
  export function isInterruptInput(input, key) {
46
34
  return (input === 'c' && key.ctrl === true) || input === '\x03';
47
35
  }
48
- export function TextInput({ placeholder, disabled, mask, historyItems = [], recordHistory = true, suggestions = [], suggestionMode = 'slash', submitOnEmpty = false, width = 80, getMentionSuggestions, onHistoryAdd, onCancel, onEscape, onToggleTasks, onResumeKey, onInterrupt, onSubmit }) {
36
+ export function TextInput({ placeholder, disabled, mask, historyItems = [], recordHistory = true, suggestions = [], suggestionMode = 'slash', submitOnEmpty = false, width = 80, inputRows = 4, suggestionRows = 6, onRowsChange, getMentionSuggestions, onHistoryAdd, onCancel, onEscape, onToggleTasks, onResumeKey, onInterrupt, onSubmit }) {
49
37
  const [value, setValue] = useState('');
50
38
  const [cursor, setCursor] = useState(0);
51
39
  const [pasteBlocks, setPasteBlocks] = useState([]);
40
+ // IME support (Ink 8): position the real terminal cursor at the editing
41
+ // point so composing text (CJK input methods) appears where the user is
42
+ // looking instead of at the frame bottom. Measured after layout commits.
43
+ const cursorHostRef = useRef(null);
44
+ const { setCursorPosition } = useCursor();
45
+ // The terminal cursor position for IME composition must use frame-origin
46
+ // coordinates (Ink's cursor basis). `useBoxMetrics`' left/top are
47
+ // parent-relative — (0,0) here, since this box sits inside DynamicFrame's
48
+ // bordered, padded input box — which pinned the hardware cursor one row
49
+ // above the input and cells behind the editing point. `measureElement()`
50
+ // accumulates ancestor offsets into frame coordinates; it is read after
51
+ // commit, when Yoga layout is final. The ref targets the input-line box (not
52
+ // the whole host), so suggestion rows rendered above it are already included
53
+ // in the measured origin.
54
+ const [inputOrigin, setInputOrigin] = useState();
55
+ useEffect(() => {
56
+ const node = cursorHostRef.current;
57
+ if (!node)
58
+ return;
59
+ const { x, y } = measureElement(node);
60
+ setInputOrigin(previous => previous && previous.x === x && previous.y === y ? previous : { x, y });
61
+ });
62
+ const screenReaderEnabled = useIsScreenReaderEnabled();
52
63
  const history = useRef(historyItems);
53
64
  const historyIndex = useRef(null);
54
65
  const draft = useRef('');
55
66
  const nextPasteId = useRef(1);
56
67
  const preferredColumn = useRef(null);
68
+ const inputRef = useRef({ value, cursor, pasteBlocks });
69
+ inputRef.current = { value, cursor, pasteBlocks };
57
70
  useEffect(() => {
58
71
  history.current = historyItems;
59
72
  }, [historyItems]);
@@ -71,16 +84,19 @@ export function TextInput({ placeholder, disabled, mask, historyItems = [], reco
71
84
  const { detectedMention, inMentionMode, filteredSuggestions, mentionList, activeMentionIndex, activeSuggestionIndex, activeSuggestion } = suggestionLayers;
72
85
  function setInput(next, nextCursor = next.length, nextPasteBlocks = []) {
73
86
  preferredColumn.current = null;
87
+ const clampedCursor = Math.max(0, Math.min(nextCursor, next.length));
88
+ inputRef.current = { value: next, cursor: clampedCursor, pasteBlocks: nextPasteBlocks };
74
89
  setValue(next);
75
- setCursor(Math.max(0, Math.min(nextCursor, next.length)));
90
+ setCursor(clampedCursor);
76
91
  setPasteBlocks(nextPasteBlocks);
77
92
  suggestionLayers.resetSelection();
78
93
  }
79
94
  function replaceInput(start, end, inserted) {
80
95
  const normalizedInserted = normalizeLineEndings(inserted);
81
- const next = value.slice(0, start) + normalizedInserted + value.slice(end);
96
+ const current = inputRef.current;
97
+ const next = current.value.slice(0, start) + normalizedInserted + current.value.slice(end);
82
98
  const insertedLineCount = lineCount(normalizedInserted);
83
- const updatedPasteBlocks = updatePasteBlocksForReplacement(pasteBlocks, start, end, normalizedInserted.length);
99
+ const updatedPasteBlocks = updatePasteBlocksForReplacement(current.pasteBlocks, start, end, normalizedInserted.length);
84
100
  const insertedPasteBlock = !mask && insertedLineCount >= COMPACT_PASTE_MIN_LINES
85
101
  ? [{ id: nextPasteId.current++, start, end: start + normalizedInserted.length, lineCount: insertedLineCount }]
86
102
  : [];
@@ -91,14 +107,20 @@ export function TextInput({ placeholder, disabled, mask, historyItems = [], reco
91
107
  historyIndex.current = index;
92
108
  setInput(history.current[index] ?? '');
93
109
  }
94
- const displayValue = mask ? '•'.repeat(value.length) : compactPasteBlocksForDisplay(value, pasteBlocks);
95
- const displayCursor = mask ? cursor : displayCursorForValueCursor(pasteBlocks, cursor);
96
- const inputWidth = Math.max(1, width - 2);
110
+ const valueGraphemes = mask ? graphemes(value) : [];
111
+ const displayValue = mask ? '•'.repeat(valueGraphemes.length) : safeInputDisplay(compactPasteBlocksForDisplay(value, pasteBlocks));
112
+ const displayCursor = mask ? valueGraphemes.filter(part => part.end <= cursor).length : displayCursorForValueCursor(pasteBlocks, cursor);
113
+ // Leave a cell for the end-of-line cursor, even on a completely full draft.
114
+ const inputWidth = Math.max(1, width - (width > 2 ? 2 : 0) - 1);
97
115
  const wrappedLines = wrapDisplayValue(displayValue, inputWidth);
98
116
  const currentCursorPosition = cursorPosition(wrappedLines, displayCursor);
117
+ function moveValueCursor(nextCursor) {
118
+ inputRef.current.cursor = nextCursor;
119
+ setCursor(nextCursor);
120
+ }
99
121
  function moveCursorToDisplayPosition(nextDisplayCursor) {
100
122
  const clampedDisplayCursor = Math.max(0, Math.min(nextDisplayCursor, displayValue.length));
101
- setCursor(mask ? clampedDisplayCursor : valueCursorForDisplayCursor(pasteBlocks, clampedDisplayCursor));
123
+ moveValueCursor(mask ? (valueGraphemes[clampedDisplayCursor]?.start ?? value.length) : valueCursorForDisplayCursor(pasteBlocks, clampedDisplayCursor));
102
124
  }
103
125
  function moveCursorVertically(direction) {
104
126
  const targetLine = wrappedLines[currentCursorPosition.lineIndex + direction];
@@ -106,20 +128,26 @@ export function TextInput({ placeholder, disabled, mask, historyItems = [], reco
106
128
  return false;
107
129
  const column = preferredColumn.current ?? currentCursorPosition.column;
108
130
  preferredColumn.current = column;
109
- moveCursorToDisplayPosition(Math.min(targetLine.start + column, targetLine.end));
131
+ moveCursorToDisplayPosition(targetLine.start + offsetAtColumn(targetLine.text, column));
110
132
  return true;
111
133
  }
112
134
  function submitValue(submitted, historyValue = submitted) {
113
- if (recordHistory && historyValue) {
135
+ if (recordHistory && !mask && historyValue) {
114
136
  if (history.current[history.current.length - 1] !== historyValue)
115
137
  history.current = [...history.current, historyValue];
116
138
  onHistoryAdd?.(historyValue);
117
139
  }
118
140
  onSubmit(submitted);
119
141
  }
120
- useInput((input, key) => {
121
- if (isKittyQueryResponseInput(input))
142
+ // Always subscribe: disabled paste is discarded, never re-routed as shortcuts.
143
+ usePaste(text => {
144
+ if (disabled)
122
145
  return;
146
+ const current = inputRef.current;
147
+ replaceInput(current.cursor, current.cursor, text);
148
+ });
149
+ useInput((input, key) => {
150
+ const { value, cursor } = inputRef.current;
123
151
  if (isInterruptInput(input, key)) {
124
152
  onInterrupt?.();
125
153
  return;
@@ -184,12 +212,12 @@ export function TextInput({ placeholder, disabled, mask, historyItems = [], reco
184
212
  }
185
213
  if (key.leftArrow) {
186
214
  preferredColumn.current = null;
187
- setCursor(current => Math.max(0, current - 1));
215
+ moveValueCursor(previousBoundary(value, cursor));
188
216
  return;
189
217
  }
190
218
  if (key.rightArrow) {
191
219
  preferredColumn.current = null;
192
- setCursor(current => Math.min(value.length, current + 1));
220
+ moveValueCursor(nextBoundary(value, cursor));
193
221
  return;
194
222
  }
195
223
  if (key.upArrow) {
@@ -229,45 +257,74 @@ export function TextInput({ placeholder, disabled, mask, historyItems = [], reco
229
257
  if (key.backspace) {
230
258
  if (cursor === 0)
231
259
  return;
232
- replaceInput(cursor - 1, cursor, '');
260
+ replaceInput(previousBoundary(value, cursor), cursor, '');
233
261
  return;
234
262
  }
235
263
  if (key.delete) {
236
264
  if (cursor >= value.length)
237
265
  return;
238
- replaceInput(cursor, cursor + 1, '');
266
+ replaceInput(cursor, nextBoundary(value, cursor), '');
239
267
  return;
240
268
  }
241
269
  if (key.ctrl && input === 'a') {
242
270
  preferredColumn.current = null;
243
- setCursor(0);
271
+ moveValueCursor(0);
244
272
  return;
245
273
  }
246
274
  if (key.ctrl && input === 'e') {
247
275
  preferredColumn.current = null;
248
- setCursor(value.length);
276
+ moveValueCursor(value.length);
249
277
  return;
250
278
  }
251
279
  if (key.ctrl && input === 'o') {
252
280
  onToggleTasks?.();
253
281
  return;
254
282
  }
283
+ if (key.ctrl)
284
+ return; // Unsupported Ctrl combinations are controls, not text.
255
285
  if (input) {
256
- replaceInput(cursor, cursor, input);
286
+ replaceInput(inputRef.current.cursor, inputRef.current.cursor, input);
257
287
  }
258
288
  });
259
- const maxVisibleLines = 4;
289
+ const maxVisibleLines = Math.max(1, inputRows);
260
290
  const firstVisibleLine = Math.max(0, Math.min(currentCursorPosition.lineIndex - maxVisibleLines + 1, wrappedLines.length - maxVisibleLines));
261
291
  const visibleLines = wrappedLines.slice(firstVisibleLine, firstVisibleLine + maxVisibleLines);
292
+ // Terminal cursor coordinates at the editing point: the input-line box's
293
+ // frame-origin position (measureElement) plus the `› ` prefix and the cell
294
+ // width of the text before the cursor (grapheme-safe via textGeometry).
295
+ let imeCursor;
296
+ if (!disabled && !screenReaderEnabled && inputOrigin) {
297
+ const visibleRow = currentCursorPosition.lineIndex - firstVisibleLine;
298
+ const line = wrappedLines[currentCursorPosition.lineIndex];
299
+ if (value.length === 0) {
300
+ imeCursor = { x: inputOrigin.x + (width > 2 ? 2 : 0), y: inputOrigin.y };
301
+ }
302
+ else if (line && visibleRow >= 0 && visibleRow < visibleLines.length) {
303
+ const lineCursorOffset = Math.max(0, Math.min(displayCursor - line.start, line.text.length));
304
+ imeCursor = {
305
+ x: inputOrigin.x + (width > 2 ? 2 : 0) + cellWidth(line.text.slice(0, lineCursorOffset)),
306
+ y: inputOrigin.y + visibleRow,
307
+ };
308
+ }
309
+ }
310
+ setCursorPosition(imeCursor);
262
311
  const displayList = inMentionMode ? mentionList : filteredSuggestions;
263
312
  const displayActiveIndex = inMentionMode ? activeMentionIndex : activeSuggestionIndex;
264
- return _jsxs(Box, { flexDirection: "column", width: "100%", children: [displayList.length > 0 && _jsx(Box, { flexDirection: "column", marginBottom: 1, children: displayList.map((suggestion, index) => _jsxs(Text, { color: index === displayActiveIndex ? theme.success : theme.muted, wrap: "truncate-end", children: [index === displayActiveIndex ? '› ' : ' ', suggestion.value, _jsxs(Text, { color: theme.muted, children: [" ", suggestion.kind ?? 'command', suggestion.description ? ` — ${suggestion.description}` : ''] })] }, suggestion.value)) }), value.length === 0 ? _jsxs(Text, { wrap: "truncate-end", children: [_jsx(Text, { color: theme.accent, children: "\u203A " }), _jsx(Text, { inverse: true, children: " " }), _jsxs(Text, { color: theme.muted, children: [" ", placeholder ?? 'Type a message...'] })] }) : visibleLines.map((line, index) => {
265
- const absoluteLineIndex = firstVisibleLine + index;
266
- const isCursorLine = absoluteLineIndex === currentCursorPosition.lineIndex;
267
- const lineCursor = isCursorLine ? Math.max(0, Math.min(displayCursor - line.start, line.text.length)) : -1;
268
- const beforeCursor = isCursorLine ? line.text.slice(0, lineCursor) : line.text;
269
- const cursorChar = isCursorLine ? line.text[lineCursor] ?? ' ' : '';
270
- const afterCursor = isCursorLine ? line.text.slice(lineCursor + 1) : '';
271
- return _jsxs(Text, { wrap: "truncate-end", children: [_jsx(Text, { color: theme.accent, children: absoluteLineIndex === 0 ? '› ' : ' ' }), isCursorLine ? _jsxs(_Fragment, { children: [beforeCursor, _jsx(Text, { inverse: true, children: cursorChar }), afterCursor] }) : line.text] }, `${line.start}-${absoluteLineIndex}`);
272
- })] });
313
+ const suggestionStart = Math.max(0, displayActiveIndex - Math.max(0, suggestionRows - 1));
314
+ const visibleSuggestions = displayList.slice(suggestionStart, suggestionStart + suggestionRows);
315
+ const wantedInputRows = Math.min(4, wrappedLines.length);
316
+ const wantedSuggestionRows = Math.min(5, displayList.length);
317
+ useEffect(() => {
318
+ onRowsChange?.({ input: wantedInputRows, suggestions: wantedSuggestionRows });
319
+ }, [onRowsChange, wantedInputRows, wantedSuggestionRows]);
320
+ return _jsxs(Box, { flexDirection: "column", width: "100%", children: [suggestionMode === 'always' ? _jsx(WizardChoices, { suggestions: displayList, activeIndex: displayActiveIndex, rows: suggestionRows }) : visibleSuggestions.length > 0 && _jsx(Box, { flexDirection: "column", children: visibleSuggestions.map((suggestion, index) => _jsxs(Text, { color: index + suggestionStart === displayActiveIndex ? theme.success : theme.muted, wrap: "truncate-end", children: [index + suggestionStart === displayActiveIndex ? '› ' : ' ', suggestion.value, _jsxs(Text, { color: theme.muted, children: [" ", suggestion.kind ?? 'command', suggestion.description ? ` — ${suggestion.description}` : ''] })] }, suggestion.value)) }), _jsx(Box, { ref: cursorHostRef, flexDirection: "column", width: "100%", children: value.length === 0 ? _jsxs(Text, { wrap: "truncate-end", children: [_jsx(Text, { color: theme.accent, children: width > 2 ? '› ' : '' }), _jsx(Text, { inverse: true, children: " " }), _jsxs(Text, { color: theme.muted, children: [" ", placeholder ?? 'Type a message...'] })] }) : visibleLines.map((line, index) => {
321
+ const absoluteLineIndex = firstVisibleLine + index;
322
+ const isCursorLine = absoluteLineIndex === currentCursorPosition.lineIndex;
323
+ const lineCursor = isCursorLine ? Math.max(0, Math.min(displayCursor - line.start, line.text.length)) : -1;
324
+ const beforeCursor = isCursorLine ? line.text.slice(0, lineCursor) : line.text;
325
+ const cursorEnd = nextBoundary(line.text, lineCursor);
326
+ const cursorChar = isCursorLine ? line.text.slice(lineCursor, cursorEnd) || ' ' : '';
327
+ const afterCursor = isCursorLine ? line.text.slice(cursorEnd) : '';
328
+ return _jsxs(Text, { wrap: "truncate-end", children: [_jsx(Text, { color: theme.accent, children: width > 2 ? (absoluteLineIndex === 0 ? '› ' : ' ') : '' }), isCursorLine ? _jsxs(_Fragment, { children: [width > 2 ? beforeCursor : '', _jsx(Text, { inverse: true, children: cellWidth(cursorChar) > inputWidth ? '�' : cursorChar }), width > 2 ? afterCursor : ''] }) : cellWidth(line.text) > inputWidth ? '�' : line.text] }, `${line.start}-${absoluteLineIndex}`);
329
+ }) })] });
273
330
  }
@@ -0,0 +1,18 @@
1
+ import React from 'react';
2
+ import { type HazeTheme } from '../theme.js';
3
+ import type { TextInputSuggestion } from './TextInput.js';
4
+ /** Rebuild from the live palette; Static transcript and terminal defaults are untouched. */
5
+ export declare function wizardChoiceTheme(palette: HazeTheme): {
6
+ components: Record<string, import("@inkjs/ui").ComponentTheme>;
7
+ };
8
+ /**
9
+ * Select's public API has no controlled focus, filter, or Tab completion. Keep
10
+ * one keyboard owner (the existing editor) and project its selected window into
11
+ * a passive library Select. This preserves free-form escape paths and avoids
12
+ * parallel listeners, private imports, and a second wizard state machine.
13
+ */
14
+ export declare function WizardChoices({ suggestions, activeIndex, rows }: {
15
+ suggestions: TextInputSuggestion[];
16
+ activeIndex: number;
17
+ rows: number;
18
+ }): React.JSX.Element | null;
@@ -0,0 +1,32 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { Select, ThemeProvider, defaultTheme, extendTheme } from '@inkjs/ui';
3
+ import { theme } from '../theme.js';
4
+ import { safeInputDisplay } from '../textGeometry.js';
5
+ /** Rebuild from the live palette; Static transcript and terminal defaults are untouched. */
6
+ export function wizardChoiceTheme(palette) {
7
+ return extendTheme(defaultTheme, { components: { Select: { styles: {
8
+ container: () => ({ flexDirection: 'column', width: '100%', overflow: 'hidden' }),
9
+ option: () => ({ height: 1, flexShrink: 0, width: '100%', overflow: 'hidden' }),
10
+ label: ({ isSelected }) => ({
11
+ color: isSelected ? palette.success : palette.muted, wrap: 'truncate-end',
12
+ }),
13
+ selectedIndicator: () => ({ display: 'none' }),
14
+ } } } });
15
+ }
16
+ /**
17
+ * Select's public API has no controlled focus, filter, or Tab completion. Keep
18
+ * one keyboard owner (the existing editor) and project its selected window into
19
+ * a passive library Select. This preserves free-form escape paths and avoids
20
+ * parallel listeners, private imports, and a second wizard state machine.
21
+ */
22
+ export function WizardChoices({ suggestions, activeIndex, rows }) {
23
+ const count = Math.max(0, Math.floor(rows));
24
+ if (count === 0 || suggestions.length === 0)
25
+ return null;
26
+ const start = Math.max(0, activeIndex - Math.max(0, count - 1));
27
+ const options = suggestions.slice(start, start + count).map((suggestion, index) => ({
28
+ value: suggestion.value,
29
+ label: safeInputDisplay(`${index + start === activeIndex ? '› ' : ' '}${suggestion.value} ${suggestion.kind ?? 'command'}${suggestion.description ? ` — ${suggestion.description}` : ''}`),
30
+ }));
31
+ return _jsx(ThemeProvider, { theme: wizardChoiceTheme(theme), children: _jsx(Select, { isDisabled: true, options: options, visibleOptionCount: count, defaultValue: suggestions[activeIndex]?.value }, `${start}:${count}:${suggestions[activeIndex]?.value}`) });
32
+ }
@@ -27,27 +27,39 @@ export function useInputSuggestions({ value, cursor, suggestions, suggestionMode
27
27
  const detectedMention = !mask && suggestionMode === 'slash' && !value.startsWith('/') && getMentionSuggestions
28
28
  ? detectMentionAtCursor(value, cursor)
29
29
  : undefined;
30
+ // Token identity binds results to the mention that produced them (SU-06): a
31
+ // previous token's list is only visible while the current token matches, so a
32
+ // fast Tab during a refetch can never complete with another token's entry.
33
+ const mentionTokenKey = detectedMention ? `${detectedMention.start}:${detectedMention.end}:${detectedMention.token}` : undefined;
34
+ const [mentionResultsFor, setMentionResultsFor] = useState();
30
35
  useEffect(() => {
31
36
  setMentionContext(detectedMention);
37
+ if (!detectedMention) {
38
+ setMentionSuggestions([]);
39
+ setMentionResultsFor(undefined);
40
+ }
32
41
  }, [detectedMention?.token, detectedMention?.start, detectedMention?.end]);
33
42
  useEffect(() => {
34
43
  if (!mentionContext || !getMentionSuggestions) {
35
- if (mentionSuggestions.length > 0)
36
- setMentionSuggestions([]);
44
+ setMentionSuggestions(current => (current.length > 0 ? [] : current));
37
45
  return;
38
46
  }
47
+ const key = `${mentionContext.start}:${mentionContext.end}:${mentionContext.token}`;
39
48
  let cancelled = false;
40
49
  Promise.resolve(getMentionSuggestions(mentionContext.token))
41
50
  .then(results => { if (!cancelled) {
42
51
  setMentionSuggestions(results);
43
52
  setMentionSelectedIndex(0);
53
+ setMentionResultsFor(key);
44
54
  } })
45
- .catch(() => { if (!cancelled)
46
- setMentionSuggestions([]); });
55
+ .catch(() => { if (!cancelled) {
56
+ setMentionSuggestions([]);
57
+ setMentionResultsFor(undefined);
58
+ } });
47
59
  return () => { cancelled = true; };
48
- }, [mentionContext?.token, mentionContext?.start, mentionContext?.end]);
60
+ }, [mentionContext?.token, mentionContext?.start, mentionContext?.end, getMentionSuggestions]);
49
61
  const inMentionMode = !!detectedMention;
50
- const mentionList = inMentionMode ? mentionSuggestions : [];
62
+ const mentionList = inMentionMode && mentionResultsFor === mentionTokenKey ? mentionSuggestions : [];
51
63
  const activeMentionIndex = Math.min(mentionSelectedIndex, Math.max(0, mentionList.length - 1));
52
64
  const activeSuggestionIndex = Math.min(selectedSuggestionIndex, Math.max(0, filteredSuggestions.length - 1));
53
65
  const activeSuggestion = inMentionMode ? mentionList[activeMentionIndex] : filteredSuggestions[activeSuggestionIndex];
@@ -1,3 +1,4 @@
1
+ import { cellWidth, graphemes } from './textGeometry.js';
1
2
  export function normalizeLineEndings(text) {
2
3
  return text.replace(/\r\n|\r/g, '\n');
3
4
  }
@@ -27,7 +28,7 @@ export function displayCursorForValueCursor(blocks, valueCursor) {
27
28
  if (valueCursor <= block.start)
28
29
  break;
29
30
  if (valueCursor < block.end)
30
- return block.start + placeholderLength;
31
+ return block.start - (valueCursor - displayCursor) + placeholderLength;
31
32
  displayCursor -= compactedLength;
32
33
  }
33
34
  return displayCursor;
@@ -67,20 +68,24 @@ export function wrapDisplayValue(displayValue, width) {
67
68
  const lines = [];
68
69
  let start = 0;
69
70
  let text = '';
70
- for (let index = 0; index < displayValue.length; index += 1) {
71
- const char = displayValue[index];
71
+ let cells = 0;
72
+ for (const { text: char, start: index } of graphemes(displayValue)) {
72
73
  if (char === '\n') {
73
74
  lines.push({ text, start, end: index });
74
75
  start = index + 1;
75
76
  text = '';
77
+ cells = 0;
76
78
  continue;
77
79
  }
78
- if (text.length >= wrapWidth) {
80
+ const charWidth = cellWidth(char);
81
+ if (text && cells + charWidth > wrapWidth) {
79
82
  lines.push({ text, start, end: index });
80
83
  start = index;
81
84
  text = '';
85
+ cells = 0;
82
86
  }
83
87
  text += char;
88
+ cells += charWidth;
84
89
  }
85
90
  lines.push({ text, start, end: displayValue.length });
86
91
  return lines;
@@ -94,6 +99,7 @@ export function cursorPosition(lines, displayCursor) {
94
99
  return displayCursor >= line.start && (displayCursor < line.end || (nextLineStartsAfterNewline && displayCursor === line.end) || (isLast && displayCursor <= line.end));
95
100
  });
96
101
  const lineIndex = Math.max(0, foundIndex);
97
- const line = lines[lineIndex] ?? lines[0] ?? { start: 0, end: 0 };
98
- return { lineIndex, column: Math.max(0, Math.min(displayCursor - line.start, line.end - line.start)) };
102
+ const line = lines[lineIndex] ?? lines[0] ?? { text: '', start: 0, end: 0 };
103
+ const offset = Math.max(0, Math.min(displayCursor - line.start, line.end - line.start));
104
+ return { lineIndex, column: cellWidth(line.text.slice(0, offset)) };
99
105
  }
@@ -0,0 +1,14 @@
1
+ import stringWidth from 'string-width';
2
+ export declare function graphemes(text: string): {
3
+ text: string;
4
+ start: number;
5
+ end: number;
6
+ }[];
7
+ export declare function previousBoundary(text: string, cursor: number): number;
8
+ export declare function nextBoundary(text: string, cursor: number): number;
9
+ /** UTF-16 offsets stay distinct from terminal-cell columns. */
10
+ export declare function offsetAtColumn(text: string, column: number): number;
11
+ export declare function clipCells(text: string, width: number): string;
12
+ /** Display-only replacement keeps offsets stable and cannot execute pasted controls. */
13
+ export declare function safeInputDisplay(text: string): string;
14
+ export { stringWidth as cellWidth };
@@ -0,0 +1,31 @@
1
+ import stringWidth from 'string-width';
2
+ const segmenter = new Intl.Segmenter(undefined, { granularity: 'grapheme' });
3
+ export function graphemes(text) {
4
+ return Array.from(segmenter.segment(text), ({ segment, index }) => ({ text: segment, start: index, end: index + segment.length }));
5
+ }
6
+ export function previousBoundary(text, cursor) {
7
+ return graphemes(text).reverse().find(part => part.start < cursor)?.start ?? 0;
8
+ }
9
+ export function nextBoundary(text, cursor) {
10
+ return graphemes(text).find(part => part.end > cursor)?.end ?? text.length;
11
+ }
12
+ /** UTF-16 offsets stay distinct from terminal-cell columns. */
13
+ export function offsetAtColumn(text, column) {
14
+ let cells = 0;
15
+ for (const part of graphemes(text)) {
16
+ const next = cells + stringWidth(part.text);
17
+ if (next > column)
18
+ return part.start;
19
+ cells = next;
20
+ }
21
+ return text.length;
22
+ }
23
+ export function clipCells(text, width) {
24
+ return text.slice(0, offsetAtColumn(text, Math.max(0, width)));
25
+ }
26
+ /** Display-only replacement keeps offsets stable and cannot execute pasted controls. */
27
+ export function safeInputDisplay(text) {
28
+ // eslint-disable-next-line no-control-regex
29
+ return text.replace(/[\x00-\x09\x0b-\x1f\x7f-\x9f]/g, '�');
30
+ }
31
+ export { stringWidth as cellWidth };
@@ -109,24 +109,45 @@ export function resolvePackageRoot(start = MODULE_DIR) {
109
109
  */
110
110
  export function gitHeadCommit(root) {
111
111
  const sha = (value) => (/^[0-9a-f]{7,40}$/i.test((value ?? '').trim()) ? value.trim() : undefined);
112
+ const readFile = (file) => {
113
+ try {
114
+ return readFileSync(file, 'utf8');
115
+ }
116
+ catch {
117
+ return undefined;
118
+ }
119
+ };
112
120
  try {
113
121
  const dotGitPath = join(root, '.git');
114
122
  const stat = statSync(dotGitPath);
123
+ // `gitdir: <path>` may be relative (resolve against the checkout root) and
124
+ // may contain spaces, so capture to end-of-line rather than \S+ (MR-05).
115
125
  const gitDir = stat.isDirectory()
116
126
  ? dotGitPath
117
- : /gitdir:\s*(\S+)/.exec(readFileSync(dotGitPath, 'utf8'))?.[1];
127
+ : resolve(root, (/gitdir:\s*(.+?)\s*$/.exec(readFile(dotGitPath) ?? '') ?? [])[1] ?? '');
118
128
  if (!gitDir)
119
129
  return undefined;
120
- const head = readFileSync(join(gitDir, 'HEAD'), 'utf8').trim();
130
+ // Linked worktrees keep refs in the common Git directory; per-worktree dirs
131
+ // carry only HEAD and private refs. Resolve via `commondir` when present.
132
+ const commonDirRaw = /\s*(.+?)\s*$/.exec(readFile(join(gitDir, 'commondir')) ?? '')?.[1];
133
+ const refDirs = commonDirRaw ? [resolve(gitDir, commonDirRaw)] : [];
134
+ const head = (readFile(join(gitDir, 'HEAD')) ?? '').trim();
121
135
  if (!head.startsWith('ref:'))
122
136
  return sha(head);
123
137
  const ref = head.slice(4).trim();
124
- const refPath = join(gitDir, ref);
125
- if (existsSync(refPath))
126
- return sha(readFileSync(refPath, 'utf8'));
127
- const packed = readFileSync(join(gitDir, 'packed-refs'), 'utf8');
128
- const escaped = ref.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
129
- return sha(new RegExp(`^([0-9a-f]{40}) ${escaped}$`, 'm').exec(packed)?.[1]);
138
+ for (const dir of [gitDir, ...refDirs]) {
139
+ const loose = sha(readFile(join(dir, ref)));
140
+ if (loose)
141
+ return loose;
142
+ const packed = readFile(join(dir, 'packed-refs'));
143
+ if (packed) {
144
+ const escaped = ref.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
145
+ const packedSha = sha(new RegExp(`^([0-9a-f]{40}) ${escaped}$`, 'm').exec(packed)?.[1]);
146
+ if (packedSha)
147
+ return packedSha;
148
+ }
149
+ }
150
+ return undefined;
130
151
  }
131
152
  catch {
132
153
  return undefined;