@asm-agent/tui 0.8.2

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 (130) hide show
  1. package/README.md +795 -0
  2. package/dist/autocomplete.d.ts +61 -0
  3. package/dist/autocomplete.d.ts.map +1 -0
  4. package/dist/autocomplete.js +601 -0
  5. package/dist/autocomplete.js.map +1 -0
  6. package/dist/components/box.d.ts +24 -0
  7. package/dist/components/box.d.ts.map +1 -0
  8. package/dist/components/box.js +114 -0
  9. package/dist/components/box.js.map +1 -0
  10. package/dist/components/cancellable-loader.d.ts +22 -0
  11. package/dist/components/cancellable-loader.d.ts.map +1 -0
  12. package/dist/components/cancellable-loader.js +35 -0
  13. package/dist/components/cancellable-loader.js.map +1 -0
  14. package/dist/components/editor.d.ts +275 -0
  15. package/dist/components/editor.d.ts.map +1 -0
  16. package/dist/components/editor.js +1968 -0
  17. package/dist/components/editor.js.map +1 -0
  18. package/dist/components/image.d.ts +34 -0
  19. package/dist/components/image.d.ts.map +1 -0
  20. package/dist/components/image.js +96 -0
  21. package/dist/components/image.js.map +1 -0
  22. package/dist/components/input.d.ts +37 -0
  23. package/dist/components/input.d.ts.map +1 -0
  24. package/dist/components/input.js +385 -0
  25. package/dist/components/input.js.map +1 -0
  26. package/dist/components/loader.d.ts +29 -0
  27. package/dist/components/loader.d.ts.map +1 -0
  28. package/dist/components/loader.js +69 -0
  29. package/dist/components/loader.js.map +1 -0
  30. package/dist/components/markdown.d.ts +100 -0
  31. package/dist/components/markdown.d.ts.map +1 -0
  32. package/dist/components/markdown.js +773 -0
  33. package/dist/components/markdown.js.map +1 -0
  34. package/dist/components/select-list.d.ts +61 -0
  35. package/dist/components/select-list.d.ts.map +1 -0
  36. package/dist/components/select-list.js +206 -0
  37. package/dist/components/select-list.js.map +1 -0
  38. package/dist/components/settings-list.d.ts +49 -0
  39. package/dist/components/settings-list.d.ts.map +1 -0
  40. package/dist/components/settings-list.js +170 -0
  41. package/dist/components/settings-list.js.map +1 -0
  42. package/dist/components/spacer.d.ts +12 -0
  43. package/dist/components/spacer.d.ts.map +1 -0
  44. package/dist/components/spacer.js +21 -0
  45. package/dist/components/spacer.js.map +1 -0
  46. package/dist/components/text.d.ts +19 -0
  47. package/dist/components/text.d.ts.map +1 -0
  48. package/dist/components/text.js +77 -0
  49. package/dist/components/text.js.map +1 -0
  50. package/dist/components/truncated-text.d.ts +14 -0
  51. package/dist/components/truncated-text.d.ts.map +1 -0
  52. package/dist/components/truncated-text.js +44 -0
  53. package/dist/components/truncated-text.js.map +1 -0
  54. package/dist/editor-component.d.ts +51 -0
  55. package/dist/editor-component.d.ts.map +1 -0
  56. package/dist/editor-component.js +2 -0
  57. package/dist/editor-component.js.map +1 -0
  58. package/dist/fullscreen.d.ts +105 -0
  59. package/dist/fullscreen.d.ts.map +1 -0
  60. package/dist/fullscreen.js +597 -0
  61. package/dist/fullscreen.js.map +1 -0
  62. package/dist/fuzzy.d.ts +26 -0
  63. package/dist/fuzzy.d.ts.map +1 -0
  64. package/dist/fuzzy.js +114 -0
  65. package/dist/fuzzy.js.map +1 -0
  66. package/dist/index.d.ts +29 -0
  67. package/dist/index.d.ts.map +1 -0
  68. package/dist/index.js +27 -0
  69. package/dist/index.js.map +1 -0
  70. package/dist/keybindings.d.ts +239 -0
  71. package/dist/keybindings.d.ts.map +1 -0
  72. package/dist/keybindings.js +222 -0
  73. package/dist/keybindings.js.map +1 -0
  74. package/dist/keys.d.ts +184 -0
  75. package/dist/keys.d.ts.map +1 -0
  76. package/dist/keys.js +1163 -0
  77. package/dist/keys.js.map +1 -0
  78. package/dist/kill-ring.d.ts +26 -0
  79. package/dist/kill-ring.d.ts.map +1 -0
  80. package/dist/kill-ring.js +42 -0
  81. package/dist/kill-ring.js.map +1 -0
  82. package/dist/latex.d.ts +21 -0
  83. package/dist/latex.d.ts.map +1 -0
  84. package/dist/latex.js +797 -0
  85. package/dist/latex.js.map +1 -0
  86. package/dist/mouse.d.ts +24 -0
  87. package/dist/mouse.d.ts.map +1 -0
  88. package/dist/mouse.js +34 -0
  89. package/dist/mouse.js.map +1 -0
  90. package/dist/render-cache.d.ts +9 -0
  91. package/dist/render-cache.d.ts.map +1 -0
  92. package/dist/render-cache.js +23 -0
  93. package/dist/render-cache.js.map +1 -0
  94. package/dist/selection-metadata.d.ts +22 -0
  95. package/dist/selection-metadata.d.ts.map +1 -0
  96. package/dist/selection-metadata.js +141 -0
  97. package/dist/selection-metadata.js.map +1 -0
  98. package/dist/slash-command-context.d.ts +12 -0
  99. package/dist/slash-command-context.d.ts.map +1 -0
  100. package/dist/slash-command-context.js +32 -0
  101. package/dist/slash-command-context.js.map +1 -0
  102. package/dist/stdin-buffer.d.ts +50 -0
  103. package/dist/stdin-buffer.d.ts.map +1 -0
  104. package/dist/stdin-buffer.js +313 -0
  105. package/dist/stdin-buffer.js.map +1 -0
  106. package/dist/terminal-colors.d.ts +31 -0
  107. package/dist/terminal-colors.d.ts.map +1 -0
  108. package/dist/terminal-colors.js +161 -0
  109. package/dist/terminal-colors.js.map +1 -0
  110. package/dist/terminal-image.d.ts +85 -0
  111. package/dist/terminal-image.d.ts.map +1 -0
  112. package/dist/terminal-image.js +324 -0
  113. package/dist/terminal-image.js.map +1 -0
  114. package/dist/terminal.d.ts +113 -0
  115. package/dist/terminal.d.ts.map +1 -0
  116. package/dist/terminal.js +486 -0
  117. package/dist/terminal.js.map +1 -0
  118. package/dist/tui.d.ts +310 -0
  119. package/dist/tui.d.ts.map +1 -0
  120. package/dist/tui.js +1673 -0
  121. package/dist/tui.js.map +1 -0
  122. package/dist/undo-stack.d.ts +16 -0
  123. package/dist/undo-stack.d.ts.map +1 -0
  124. package/dist/undo-stack.js +26 -0
  125. package/dist/undo-stack.js.map +1 -0
  126. package/dist/utils.d.ts +98 -0
  127. package/dist/utils.d.ts.map +1 -0
  128. package/dist/utils.js +1233 -0
  129. package/dist/utils.js.map +1 -0
  130. package/package.json +52 -0
package/README.md ADDED
@@ -0,0 +1,795 @@
1
+ <pre align="center">
2
+ +----------+
3
+ / /|
4
+ +----------+ |
5
+ | | |
6
+ | |/
7
+ +----------+
8
+ </pre>
9
+
10
+ <h1 align="center">ASM Agent TUI</h1>
11
+
12
+ <p align="center">
13
+ Terminal UI primitives.
14
+ </p>
15
+
16
+ Release docs use the ASM Agent package name. The source workspace manifest still keeps an inherited package name until the namespace migration is complete.
17
+
18
+ Minimal terminal UI framework with differential rendering and synchronized output for flicker-free interactive CLI applications.
19
+
20
+ ## Features
21
+
22
+ - **Differential Rendering**: Three-strategy rendering system that only updates what changed
23
+ - **Synchronized Output**: Uses CSI 2026 for atomic screen updates (no flicker)
24
+ - **Bracketed Paste Mode**: Handles large pastes correctly with markers for >10 line pastes
25
+ - **Component-based**: Simple Component interface with render() method
26
+ - **Theme Support**: Components accept theme interfaces for customizable styling
27
+ - **Built-in Components**: Text, TruncatedText, Input, Editor, Markdown, Loader, SelectList, SettingsList, Spacer, Image, Box, Container
28
+ - **Image Support**: Renders terminal graphics or compact image metadata
29
+ - **Autocomplete Support**: File paths and slash commands
30
+
31
+ ## Quick Start
32
+
33
+ ```typescript
34
+ import { TUI, Text, Editor, ProcessTerminal, matchesKey } from "asm-agent-tui";
35
+
36
+ // Create terminal
37
+ const terminal = new ProcessTerminal();
38
+
39
+ // Create TUI
40
+ const tui = new TUI(terminal);
41
+
42
+ // Add components
43
+ tui.addChild(new Text("Welcome to my app!"));
44
+
45
+ import { defaultEditorTheme as editorTheme } from './test/test-themes.ts';
46
+ const editor = new Editor(tui, editorTheme);
47
+ editor.onSubmit = (text) => {
48
+ console.log("Submitted:", text);
49
+ tui.addChild(new Text(`You said: ${text}`));
50
+ };
51
+ tui.addChild(editor);
52
+
53
+ // Focus the editor so it receives keyboard input
54
+ tui.setFocus(editor);
55
+
56
+ // In raw mode Ctrl+C doesn't send SIGINT — intercept it here to allow exit
57
+ tui.addInputListener((data) => {
58
+ if (matchesKey(data, 'ctrl+c')) {
59
+ tui.stop();
60
+ process.exit(0);
61
+ }
62
+ });
63
+
64
+ // Start
65
+ tui.start();
66
+ ```
67
+
68
+ ## Core API
69
+
70
+ ### TUI
71
+
72
+ Main container that manages components and rendering.
73
+
74
+ ```typescript
75
+ const tui = new TUI(terminal);
76
+ tui.addChild(component);
77
+ tui.removeChild(component);
78
+ tui.start();
79
+ tui.stop();
80
+ tui.requestRender(); // Request a re-render
81
+
82
+ // Global debug key handler (Shift+Ctrl+D)
83
+ tui.onDebug = () => console.log("Debug triggered");
84
+ ```
85
+
86
+ ### Overlays
87
+
88
+ Overlays render components on top of existing content without replacing it. Useful for dialogs, menus, and modal UI.
89
+
90
+ ```typescript
91
+ // Show overlay with default options (centered, max 80 cols)
92
+ const handle = tui.showOverlay(component);
93
+
94
+ // Show overlay with custom positioning and sizing
95
+ // Values can be numbers (absolute) or percentage strings (e.g., "50%")
96
+ const handle = tui.showOverlay(component, {
97
+ // Sizing
98
+ width: 60, // Fixed width in columns
99
+ width: "80%", // Width as percentage of terminal
100
+ minWidth: 40, // Minimum width floor
101
+ maxHeight: 20, // Maximum height in rows
102
+ maxHeight: "50%", // Maximum height as percentage of terminal
103
+
104
+ // Anchor-based positioning (default: 'center')
105
+ anchor: 'bottom-right', // Position relative to anchor point
106
+ offsetX: 2, // Horizontal offset from anchor
107
+ offsetY: -1, // Vertical offset from anchor
108
+
109
+ // Percentage-based positioning (alternative to anchor)
110
+ row: "25%", // Vertical position (0%=top, 100%=bottom)
111
+ col: "50%", // Horizontal position (0%=left, 100%=right)
112
+
113
+ // Absolute positioning (overrides anchor/percent)
114
+ row: 5, // Exact row position
115
+ col: 10, // Exact column position
116
+
117
+ // Margin from terminal edges
118
+ margin: 2, // All sides
119
+ margin: { top: 1, right: 2, bottom: 1, left: 2 },
120
+
121
+ // Responsive visibility
122
+ visible: (termWidth, termHeight) => termWidth >= 100 // Hide on narrow terminals
123
+
124
+ // Focus behavior
125
+ nonCapturing: true // Don't auto-focus when shown
126
+ });
127
+
128
+ // OverlayHandle methods
129
+ handle.hide(); // Permanently remove the overlay
130
+ handle.setHidden(true); // Temporarily hide (can show again)
131
+ handle.setHidden(false); // Show again after hiding
132
+ handle.isHidden(); // Check if temporarily hidden
133
+ handle.focus(); // Focus and bring to visual front
134
+ handle.unfocus(); // Release focus to previous target
135
+ handle.isFocused(); // Check if overlay has focus
136
+
137
+ // Hide topmost overlay
138
+ tui.hideOverlay();
139
+
140
+ // Check if any visible overlay is active
141
+ tui.hasOverlay();
142
+ ```
143
+
144
+ **Anchor values**: `'center'`, `'top-left'`, `'top-right'`, `'bottom-left'`, `'bottom-right'`, `'top-center'`, `'bottom-center'`, `'left-center'`, `'right-center'`
145
+
146
+ **Resolution order**:
147
+ 1. `minWidth` is applied as a floor after width calculation
148
+ 2. For position: absolute `row`/`col` > percentage `row`/`col` > `anchor`
149
+ 3. `margin` clamps final position to stay within terminal bounds
150
+ 4. `visible` callback controls whether overlay renders (called each frame)
151
+
152
+ ### Component Interface
153
+
154
+ All components implement:
155
+
156
+ ```typescript
157
+ interface Component {
158
+ render(width: number): string[];
159
+ handleInput?(data: string): void;
160
+ invalidate?(): void;
161
+ }
162
+ ```
163
+
164
+ | Method | Description |
165
+ |--------|-------------|
166
+ | `render(width)` | Returns an array of strings, one per line. Each line **must not exceed `width`** or the TUI will error. Use `truncateToWidth()` or manual wrapping to ensure this. |
167
+ | `handleInput?(data)` | Called when the component has focus and receives keyboard input. The `data` string contains raw terminal input (may include ANSI escape sequences). |
168
+ | `invalidate?()` | Called to clear any cached render state. Components should re-render from scratch on the next `render()` call. |
169
+
170
+ The TUI appends a full SGR reset and OSC 8 reset at the end of each rendered line. Styles do not carry across lines. If you emit multi-line text with styling, reapply styles per line or use `wrapTextWithAnsi()` so styles are preserved for each wrapped line.
171
+
172
+ ### Focusable Interface (IME Support)
173
+
174
+ Components that display a text cursor and need IME (Input Method Editor) support should implement the `Focusable` interface:
175
+
176
+ ```typescript
177
+ import { CURSOR_MARKER, type Component, type Focusable } from "asm-agent-tui";
178
+
179
+ class MyInput implements Component, Focusable {
180
+ focused: boolean = false; // Set by TUI when focus changes
181
+
182
+ render(width: number): string[] {
183
+ const marker = this.focused ? CURSOR_MARKER : "";
184
+ // Emit marker right before the fake cursor
185
+ return [`> ${beforeCursor}${marker}\x1b[7m${atCursor}\x1b[27m${afterCursor}`];
186
+ }
187
+ }
188
+ ```
189
+
190
+ When a `Focusable` component has focus, TUI:
191
+ 1. Sets `focused = true` on the component
192
+ 2. Scans rendered output for `CURSOR_MARKER` (a zero-width APC escape sequence)
193
+ 3. Positions the hardware terminal cursor at that location
194
+ 4. Shows the hardware cursor
195
+
196
+ This enables IME candidate windows to appear at the correct position for CJK input methods. The `Editor` and `Input` built-in components already implement this interface.
197
+
198
+ **Container components with embedded inputs:** When a container component (dialog, selector, etc.) contains an `Input` or `Editor` child, the container must implement `Focusable` and propagate the focus state to the child:
199
+
200
+ ```typescript
201
+ import { Container, type Focusable, Input } from "asm-agent-tui";
202
+
203
+ class SearchDialog extends Container implements Focusable {
204
+ private searchInput: Input;
205
+
206
+ // Propagate focus to child input for IME cursor positioning
207
+ private _focused = false;
208
+ get focused(): boolean { return this._focused; }
209
+ set focused(value: boolean) {
210
+ this._focused = value;
211
+ this.searchInput.focused = value;
212
+ }
213
+
214
+ constructor() {
215
+ super();
216
+ this.searchInput = new Input();
217
+ this.addChild(this.searchInput);
218
+ }
219
+ }
220
+ ```
221
+
222
+ Without this propagation, typing with an IME (Chinese, Japanese, Korean, etc.) will show the candidate window in the wrong position.
223
+
224
+ ## Built-in Components
225
+
226
+ ### Container
227
+
228
+ Groups child components.
229
+
230
+ ```typescript
231
+ const container = new Container();
232
+ container.addChild(component);
233
+ container.removeChild(component);
234
+ ```
235
+
236
+ ### Box
237
+
238
+ Container that applies padding and background color to all children.
239
+
240
+ ```typescript
241
+ const box = new Box(
242
+ 1, // paddingX (default: 1)
243
+ 1, // paddingY (default: 1)
244
+ (text) => chalk.bgGray(text) // optional background function
245
+ );
246
+ box.addChild(new Text("Content"));
247
+ box.setBgFn((text) => chalk.bgBlue(text)); // Change background dynamically
248
+ ```
249
+
250
+ ### Text
251
+
252
+ Displays multi-line text with word wrapping and padding.
253
+
254
+ ```typescript
255
+ const text = new Text(
256
+ "Hello World", // text content
257
+ 1, // paddingX (default: 1)
258
+ 1, // paddingY (default: 1)
259
+ (text) => chalk.bgGray(text) // optional background function
260
+ );
261
+ text.setText("Updated text");
262
+ text.setCustomBgFn((text) => chalk.bgBlue(text));
263
+ ```
264
+
265
+ ### TruncatedText
266
+
267
+ Single-line text that truncates to fit viewport width. Useful for status lines and headers.
268
+
269
+ ```typescript
270
+ const truncated = new TruncatedText(
271
+ "This is a very long line that will be truncated...",
272
+ 0, // paddingX (default: 0)
273
+ 0 // paddingY (default: 0)
274
+ );
275
+ ```
276
+
277
+ ### Input
278
+
279
+ Single-line text input with horizontal scrolling.
280
+
281
+ ```typescript
282
+ const input = new Input();
283
+ input.onSubmit = (value) => console.log(value);
284
+ input.setValue("initial");
285
+ input.getValue();
286
+ ```
287
+
288
+ **Key Bindings:**
289
+ - `Enter` - Submit
290
+ - `Ctrl+A` / `Ctrl+E` - Line start/end
291
+ - `Ctrl+W` or `Alt+Backspace` - Delete word backwards
292
+ - `Ctrl+U` - Delete to start of line
293
+ - `Ctrl+K` - Delete to end of line
294
+ - `Ctrl+Left` / `Ctrl+Right` - Word navigation
295
+ - `Alt+Left` / `Alt+Right` - Word navigation
296
+ - Arrow keys, Backspace, Delete work as expected
297
+
298
+ ### Editor
299
+
300
+ Multi-line text editor with autocomplete, file completion, paste handling, and vertical scrolling when content exceeds terminal height.
301
+
302
+ ```typescript
303
+ interface EditorTheme {
304
+ borderColor: (str: string) => string;
305
+ selectList: SelectListTheme;
306
+ }
307
+
308
+ interface EditorOptions {
309
+ paddingX?: number; // Horizontal padding (default: 0)
310
+ }
311
+
312
+ const editor = new Editor(tui, theme, options?); // tui is required for height-aware scrolling
313
+ editor.onSubmit = (text) => console.log(text);
314
+ editor.onChange = (text) => console.log("Changed:", text);
315
+ editor.disableSubmit = true; // Disable submit temporarily
316
+ editor.setAutocompleteProvider(provider);
317
+ editor.borderColor = (s) => chalk.blue(s); // Change border dynamically
318
+ editor.setPaddingX(1); // Update horizontal padding dynamically
319
+ editor.getPaddingX(); // Get current padding
320
+ ```
321
+
322
+ **Features:**
323
+ - Multi-line editing with word wrap
324
+ - Slash command autocomplete (type `/`)
325
+ - File path autocomplete (press `Tab`)
326
+ - Large paste handling (>10 lines creates `[paste #1 +50 lines]` marker)
327
+ - Horizontal lines above/below editor
328
+ - Fake cursor rendering (hidden real cursor)
329
+
330
+ **Key Bindings:**
331
+ - `Enter` - Submit
332
+ - `Shift+Enter`, `Ctrl+Enter`, or `Alt+Enter` - New line (terminal-dependent, Alt+Enter most reliable)
333
+ - `Tab` - Autocomplete
334
+ - `Ctrl+K` - Delete to end of line
335
+ - `Ctrl+U` - Delete to start of line
336
+ - `Ctrl+W` or `Alt+Backspace` - Delete word backwards
337
+ - `Alt+D` or `Alt+Delete` - Delete word forwards
338
+ - `Ctrl+A` / `Ctrl+E` - Line start/end
339
+ - `Ctrl+]` - Jump forward to character (awaits next keypress, then moves cursor to first occurrence)
340
+ - `Ctrl+Alt+]` - Jump backward to character
341
+ - Arrow keys, Backspace, Delete work as expected
342
+
343
+ ### Markdown
344
+
345
+ Renders markdown with syntax highlighting and theming support.
346
+
347
+ ```typescript
348
+ interface MarkdownTheme {
349
+ heading: (text: string) => string;
350
+ link: (text: string) => string;
351
+ linkUrl: (text: string) => string;
352
+ code: (text: string) => string;
353
+ codeBlock: (text: string) => string;
354
+ codeBlockBorder: (text: string) => string;
355
+ quote: (text: string) => string;
356
+ quoteBorder: (text: string) => string;
357
+ hr: (text: string) => string;
358
+ listBullet: (text: string) => string;
359
+ bold: (text: string) => string;
360
+ italic: (text: string) => string;
361
+ strikethrough: (text: string) => string;
362
+ underline: (text: string) => string;
363
+ highlightCode?: (code: string, lang?: string) => string[];
364
+ }
365
+
366
+ interface DefaultTextStyle {
367
+ color?: (text: string) => string;
368
+ bgColor?: (text: string) => string;
369
+ bold?: boolean;
370
+ italic?: boolean;
371
+ strikethrough?: boolean;
372
+ underline?: boolean;
373
+ }
374
+
375
+ const md = new Markdown(
376
+ "# Hello\n\nSome **bold** text",
377
+ 1, // paddingX
378
+ 1, // paddingY
379
+ theme, // MarkdownTheme
380
+ defaultStyle // optional DefaultTextStyle
381
+ );
382
+ md.setText("Updated markdown");
383
+ ```
384
+
385
+ **Features:**
386
+ - Headings, bold, italic, code blocks, lists, links, blockquotes
387
+ - HTML tags rendered as plain text
388
+ - Optional syntax highlighting via `highlightCode`
389
+ - Padding support
390
+ - Render caching for performance
391
+
392
+ ### Loader
393
+
394
+ Animated loading spinner.
395
+
396
+ ```typescript
397
+ const loader = new Loader(
398
+ tui, // TUI instance for render updates
399
+ (s) => chalk.cyan(s), // spinner color function
400
+ (s) => chalk.gray(s), // message color function
401
+ "Loading..." // message (default: "Loading...")
402
+ );
403
+ loader.start();
404
+ loader.setMessage("Still loading...");
405
+ loader.stop();
406
+ ```
407
+
408
+ ### CancellableLoader
409
+
410
+ Extends Loader with Escape key handling and an AbortSignal for cancelling async operations.
411
+
412
+ ```typescript
413
+ const loader = new CancellableLoader(
414
+ tui, // TUI instance for render updates
415
+ (s) => chalk.cyan(s), // spinner color function
416
+ (s) => chalk.gray(s), // message color function
417
+ "Working..." // message
418
+ );
419
+ loader.onAbort = () => done(null); // Called when user presses Escape
420
+ doAsyncWork(loader.signal).then(done);
421
+ ```
422
+
423
+ **Properties:**
424
+ - `signal: AbortSignal` - Aborted when user presses Escape
425
+ - `aborted: boolean` - Whether the loader was aborted
426
+ - `onAbort?: () => void` - Callback when user presses Escape
427
+
428
+ ### SelectList
429
+
430
+ Interactive selection list with keyboard navigation.
431
+
432
+ ```typescript
433
+ interface SelectItem {
434
+ value: string;
435
+ label: string;
436
+ description?: string;
437
+ }
438
+
439
+ interface SelectListTheme {
440
+ selectedPrefix: (text: string) => string;
441
+ selectedText: (text: string) => string;
442
+ description: (text: string) => string;
443
+ scrollInfo: (text: string) => string;
444
+ noMatch: (text: string) => string;
445
+ }
446
+
447
+ const list = new SelectList(
448
+ [
449
+ { value: "opt1", label: "Option 1", description: "First option" },
450
+ { value: "opt2", label: "Option 2", description: "Second option" },
451
+ ],
452
+ 5, // maxVisible
453
+ theme // SelectListTheme
454
+ );
455
+
456
+ list.onSelect = (item) => console.log("Selected:", item);
457
+ list.onCancel = () => console.log("Cancelled");
458
+ list.onSelectionChange = (item) => console.log("Highlighted:", item);
459
+ list.setFilter("opt"); // Filter items
460
+ ```
461
+
462
+ **Controls:**
463
+ - Arrow keys: Navigate
464
+ - Enter: Select
465
+ - Escape: Cancel
466
+
467
+ ### SettingsList
468
+
469
+ Settings panel with value cycling and submenus.
470
+
471
+ ```typescript
472
+ interface SettingItem {
473
+ id: string;
474
+ label: string;
475
+ description?: string;
476
+ currentValue: string;
477
+ values?: string[]; // If provided, Enter/Space cycles through these
478
+ submenu?: (currentValue: string, done: (selectedValue?: string) => void) => Component;
479
+ }
480
+
481
+ interface SettingsListTheme {
482
+ label: (text: string, selected: boolean) => string;
483
+ value: (text: string, selected: boolean) => string;
484
+ description: (text: string) => string;
485
+ cursor: string;
486
+ hint: (text: string) => string;
487
+ }
488
+
489
+ const settings = new SettingsList(
490
+ [
491
+ { id: "theme", label: "Theme", currentValue: "dark", values: ["dark", "light"] },
492
+ { id: "model", label: "Model", currentValue: "gpt-4", submenu: (val, done) => modelSelector },
493
+ ],
494
+ 10, // maxVisible
495
+ theme, // SettingsListTheme
496
+ (id, newValue) => console.log(`${id} changed to ${newValue}`),
497
+ () => console.log("Cancelled")
498
+ );
499
+ settings.updateValue("theme", "light");
500
+ ```
501
+
502
+ **Controls:**
503
+ - Arrow keys: Navigate
504
+ - Enter/Space: Activate (cycle value or open submenu)
505
+ - Escape: Cancel
506
+
507
+ ### Spacer
508
+
509
+ Empty lines for vertical spacing.
510
+
511
+ ```typescript
512
+ const spacer = new Spacer(2); // 2 empty lines (default: 1)
513
+ ```
514
+
515
+ ### Image
516
+
517
+ Renders Kitty or iTerm2 terminal graphics when supported. Set `fallbackOnly: true` to show compact image metadata instead; ASM Agent uses this metadata-only mode.
518
+
519
+ ```typescript
520
+ interface ImageTheme {
521
+ fallbackColor: (str: string) => string;
522
+ }
523
+
524
+ interface ImageOptions {
525
+ maxWidthCells?: number;
526
+ maxHeightCells?: number;
527
+ filename?: string;
528
+ fallbackOnly?: boolean;
529
+ }
530
+
531
+ const image = new Image(
532
+ base64Data, // base64-encoded image data
533
+ "image/png", // MIME type
534
+ theme, // ImageTheme
535
+ options // optional ImageOptions
536
+ );
537
+ tui.addChild(image);
538
+ ```
539
+
540
+ Supported formats: PNG, JPEG, GIF, WebP. Dimensions are parsed from the image headers automatically.
541
+
542
+ ## Autocomplete
543
+
544
+ ### CombinedAutocompleteProvider
545
+
546
+ Supports both slash commands and file paths.
547
+
548
+ ```typescript
549
+ import { CombinedAutocompleteProvider } from "asm-agent-tui";
550
+
551
+ const provider = new CombinedAutocompleteProvider(
552
+ [
553
+ { name: "help", description: "Show help" },
554
+ { name: "clear", description: "Clear screen" },
555
+ { name: "delete", description: "Delete last message" },
556
+ ],
557
+ process.cwd() // base path for file completion
558
+ );
559
+
560
+ editor.setAutocompleteProvider(provider);
561
+ ```
562
+
563
+ **Features:**
564
+ - Type `/` to see slash commands
565
+ - Press `Tab` for file path completion
566
+ - Works with `~/`, `./`, `../`, and `@` prefix
567
+ - Filters to attachable files for `@` prefix
568
+
569
+ ## Key Detection
570
+
571
+ Use `matchesKey()` with the `Key` helper for detecting keyboard input (supports Kitty keyboard protocol):
572
+
573
+ ```typescript
574
+ import { matchesKey, Key } from "asm-agent-tui";
575
+
576
+ if (matchesKey(data, Key.ctrl("c"))) {
577
+ process.exit(0);
578
+ }
579
+
580
+ if (matchesKey(data, Key.enter)) {
581
+ submit();
582
+ } else if (matchesKey(data, Key.escape)) {
583
+ cancel();
584
+ } else if (matchesKey(data, Key.up)) {
585
+ moveUp();
586
+ }
587
+ ```
588
+
589
+ **Key identifiers** (use `Key.*` for autocomplete, or string literals):
590
+ - Basic keys: `Key.enter`, `Key.escape`, `Key.tab`, `Key.space`, `Key.backspace`, `Key.delete`, `Key.home`, `Key.end`
591
+ - Arrow keys: `Key.up`, `Key.down`, `Key.left`, `Key.right`
592
+ - With modifiers: `Key.ctrl("c")`, `Key.shift("tab")`, `Key.alt("left")`, `Key.ctrlShift("p")`
593
+ - String format also works: `"enter"`, `"ctrl+c"`, `"shift+tab"`, `"ctrl+shift+p"`
594
+
595
+ ## Differential Rendering
596
+
597
+ The TUI uses three rendering strategies:
598
+
599
+ 1. **First Render**: Output all lines without clearing scrollback
600
+ 2. **Width Changed or Change Above Viewport**: Clear screen and full re-render
601
+ 3. **Normal Update**: Move cursor to first changed line, clear to end, render changed lines
602
+
603
+ All updates are wrapped in **synchronized output** (`\x1b[?2026h` ... `\x1b[?2026l`) for atomic, flicker-free rendering.
604
+
605
+ ## Terminal Interface
606
+
607
+ The TUI works with any object implementing the `Terminal` interface:
608
+
609
+ ```typescript
610
+ interface Terminal {
611
+ start(onInput: (data: string) => void, onResize: () => void): void;
612
+ stop(): void;
613
+ write(data: string): void;
614
+ get columns(): number;
615
+ get rows(): number;
616
+ moveBy(lines: number): void;
617
+ hideCursor(): void;
618
+ showCursor(): void;
619
+ clearLine(): void;
620
+ clearFromCursor(): void;
621
+ clearScreen(): void;
622
+ }
623
+ ```
624
+
625
+ **Built-in implementations:**
626
+ - `ProcessTerminal` - Uses `process.stdin/stdout`
627
+ - `VirtualTerminal` - For testing (uses `@xterm/headless`)
628
+
629
+ ## Utilities
630
+
631
+ ```typescript
632
+ import { visibleWidth, truncateToWidth, wrapTextWithAnsi } from "asm-agent-tui";
633
+
634
+ // Get visible width of string (ignoring ANSI codes)
635
+ const width = visibleWidth("\x1b[31mHello\x1b[0m"); // 5
636
+
637
+ // Truncate string to width (preserving ANSI codes, adds ellipsis)
638
+ const truncated = truncateToWidth("Hello World", 8); // "Hello..."
639
+
640
+ // Truncate without ellipsis
641
+ const truncatedNoEllipsis = truncateToWidth("Hello World", 8, ""); // "Hello Wo"
642
+
643
+ // Wrap text to width (preserving ANSI codes across line breaks)
644
+ const lines = wrapTextWithAnsi("This is a long line that needs wrapping", 20);
645
+ // ["This is a long line", "that needs wrapping"]
646
+ ```
647
+
648
+ ## Creating Custom Components
649
+
650
+ When creating custom components, **each line returned by `render()` must not exceed the `width` parameter**. The TUI will error if any line is wider than the terminal.
651
+
652
+ ### Handling Input
653
+
654
+ Use `matchesKey()` with the `Key` helper for keyboard input:
655
+
656
+ ```typescript
657
+ import { matchesKey, Key, truncateToWidth } from "asm-agent-tui";
658
+ import type { Component } from "asm-agent-tui";
659
+
660
+ class MyInteractiveComponent implements Component {
661
+ private selectedIndex = 0;
662
+ private items = ["Option 1", "Option 2", "Option 3"];
663
+
664
+ public onSelect?: (index: number) => void;
665
+ public onCancel?: () => void;
666
+
667
+ handleInput(data: string): void {
668
+ if (matchesKey(data, Key.up)) {
669
+ this.selectedIndex = Math.max(0, this.selectedIndex - 1);
670
+ } else if (matchesKey(data, Key.down)) {
671
+ this.selectedIndex = Math.min(this.items.length - 1, this.selectedIndex + 1);
672
+ } else if (matchesKey(data, Key.enter)) {
673
+ this.onSelect?.(this.selectedIndex);
674
+ } else if (matchesKey(data, Key.escape) || matchesKey(data, Key.ctrl("c"))) {
675
+ this.onCancel?.();
676
+ }
677
+ }
678
+
679
+ render(width: number): string[] {
680
+ return this.items.map((item, i) => {
681
+ const prefix = i === this.selectedIndex ? "> " : " ";
682
+ return truncateToWidth(prefix + item, width);
683
+ });
684
+ }
685
+ }
686
+ ```
687
+
688
+ ### Handling Line Width
689
+
690
+ Use the provided utilities to ensure lines fit:
691
+
692
+ ```typescript
693
+ import { visibleWidth, truncateToWidth } from "asm-agent-tui";
694
+ import type { Component } from "asm-agent-tui";
695
+
696
+ class MyComponent implements Component {
697
+ private text: string;
698
+
699
+ constructor(text: string) {
700
+ this.text = text;
701
+ }
702
+
703
+ render(width: number): string[] {
704
+ // Option 1: Truncate long lines
705
+ return [truncateToWidth(this.text, width)];
706
+
707
+ // Option 2: Check and pad to exact width
708
+ const line = this.text;
709
+ const visible = visibleWidth(line);
710
+ if (visible > width) {
711
+ return [truncateToWidth(line, width)];
712
+ }
713
+ // Pad to exact width (optional, for backgrounds)
714
+ return [line + " ".repeat(width - visible)];
715
+ }
716
+ }
717
+ ```
718
+
719
+ ### ANSI Code Considerations
720
+
721
+ Both `visibleWidth()` and `truncateToWidth()` correctly handle ANSI escape codes:
722
+
723
+ - `visibleWidth()` ignores ANSI codes when calculating width
724
+ - `truncateToWidth()` preserves ANSI codes and properly closes them when truncating
725
+
726
+ ```typescript
727
+ import chalk from "chalk";
728
+
729
+ const styled = chalk.red("Hello") + " " + chalk.blue("World");
730
+ const width = visibleWidth(styled); // 11 (not counting ANSI codes)
731
+ const truncated = truncateToWidth(styled, 8); // Red "Hello" + " W..." with proper reset
732
+ ```
733
+
734
+ ### Caching
735
+
736
+ For performance, components should cache their rendered output and only re-render when necessary:
737
+
738
+ ```typescript
739
+ class CachedComponent implements Component {
740
+ private text: string;
741
+ private cachedWidth?: number;
742
+ private cachedLines?: string[];
743
+
744
+ render(width: number): string[] {
745
+ if (this.cachedLines && this.cachedWidth === width) {
746
+ return this.cachedLines;
747
+ }
748
+
749
+ const lines = [truncateToWidth(this.text, width)];
750
+
751
+ this.cachedWidth = width;
752
+ this.cachedLines = lines;
753
+ return lines;
754
+ }
755
+
756
+ invalidate(): void {
757
+ this.cachedWidth = undefined;
758
+ this.cachedLines = undefined;
759
+ }
760
+ }
761
+ ```
762
+
763
+ ## Example
764
+
765
+ See `test/chat-simple.ts` for a complete chat interface example with:
766
+ - Markdown messages with custom background colors
767
+ - Loading spinner during responses
768
+ - Editor with autocomplete and slash commands
769
+ - Spacers between messages
770
+
771
+ Run it:
772
+ ```bash
773
+ npx tsx test/chat-simple.ts
774
+ ```
775
+
776
+ ## Development
777
+
778
+ ```bash
779
+ # Install dependencies (from monorepo root)
780
+ npm install
781
+
782
+ # Run type checking
783
+ npm run check
784
+
785
+ # Run the demo
786
+ npx tsx test/chat-simple.ts
787
+ ```
788
+
789
+ ### Debug logging
790
+
791
+ Set `PI_TUI_WRITE_LOG` to capture the raw ANSI stream written to stdout.
792
+
793
+ ```bash
794
+ PI_TUI_WRITE_LOG=/tmp/tui-ansi.log npx tsx test/chat-simple.ts
795
+ ```