{"_id":"@aos-agent/tui","_rev":"4-94d183ee89918f5fb92665e329417f51","name":"@aos-agent/tui","dist-tags":{"latest":"0.85.1"},"versions":{"0.84.2":{"name":"@aos-agent/tui","version":"0.84.2","keywords":["tui","terminal","ui","text-editor","differential-rendering","typescript","cli"],"author":{"name":"Mario Zechner"},"license":"MIT","_id":"@aos-agent/tui@0.84.2","maintainers":[{"name":"aosagent","email":"guanwenpeng2001@gmail.com"}],"homepage":"https://github.com/guanwenpeng2001-bot/AOS-Agent#readme","bugs":{"url":"https://github.com/guanwenpeng2001-bot/AOS-Agent/issues"},"dist":{"shasum":"179c4a1e924287125e8a8df888611bbb15864c22","tarball":"https://registry.npmjs.org/@aos-agent/tui/-/tui-0.84.2.tgz","fileCount":164,"integrity":"sha512-J37w91fxLy21+Kn4S2ZCM55Hy+bIzX4czsQqTiB8wEWsJfxOrZsrG+manZJx5Xev2N0aPLuISjsY5EnO46NSDQ==","signatures":[{"sig":"MEYCIQCcscVOPvAJcTKSyZ68nMjQ01sfDvTZv4YLDeFemyiVmQIhAMA5HTHgQwtghx+UFNzf7xBcXyksOiQ4/ZTOgp5EF6wh","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":2393138},"main":"dist/index.js","type":"module","types":"./dist/index.d.ts","engines":{"node":">=22.19.0"},"scripts":{"test":"node --test --test-reporter=dot --test-reporter-destination=stdout test/*.test.ts","build":"tsgo -p tsconfig.build.json","clean":"shx rm -rf dist","prepublishOnly":"npm run clean && npm run build","build:native:win32":"node native/win32/build.mjs","build:native:darwin":"native/darwin/build.sh"},"_npmUser":{"name":"aosagent","email":"guanwenpeng2001@gmail.com"},"repository":{"url":"git+https://github.com/guanwenpeng2001-bot/AOS-Agent.git","type":"git","directory":"packages/tui"},"_npmVersion":"12.0.2","description":"Terminal User Interface library with differential rendering for efficient text-based applications","directories":{},"_nodeVersion":"24.18.1","dependencies":{"marked":"18.0.5","get-east-asian-width":"1.6.0"},"_hasShrinkwrap":false,"devDependencies":{"chalk":"5.6.2","@xterm/headless":"5.5.0"},"_npmOperationalInternal":{"tmp":"tmp/tui_0.84.2_1786323848483_0.04465623730010826","host":"s3://npm-registry-packages-npm-production"}},"0.84.3":{"name":"@aos-agent/tui","version":"0.84.3","keywords":["tui","terminal","ui","text-editor","differential-rendering","typescript","cli"],"author":{"name":"Mario Zechner"},"license":"MIT","_id":"@aos-agent/tui@0.84.3","maintainers":[{"name":"aosagent","email":"guanwenpeng2001@gmail.com"}],"homepage":"https://github.com/guanwenpeng2001-bot/AOS-Agent#readme","bugs":{"url":"https://github.com/guanwenpeng2001-bot/AOS-Agent/issues"},"dist":{"shasum":"83c2ce1f001a9849e963dff6d73181ddf79dca4c","tarball":"https://registry.npmjs.org/@aos-agent/tui/-/tui-0.84.3.tgz","fileCount":164,"integrity":"sha512-f0APp6+Yyn1v8VuFAlTKZDoOeMW8ZiQR3cwDnP2kdEwDxBgyT9ogygfJ6OFS76PDYdT8erxCv0CqH9JfFzwBtg==","signatures":[{"sig":"MEYCIQDn6h6MJ6sIRIn80SBEldVEc4P1cOv/VzS6mBJK3Glw6gIhAIJ9HqKvC+n47pGJ04XUwMK7n/3fd1zRQvFy9CWM7OL4","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"attestations":{"url":"https://registry.npmjs.org/-/npm/v1/attestations/@aos-agent%2ftui@0.84.3","provenance":{"predicateType":"https://slsa.dev/provenance/v1"}},"unpackedSize":2393138},"main":"dist/index.js","type":"module","types":"./dist/index.d.ts","engines":{"node":">=22.19.0"},"gitHead":"d92430128236cc1f285dcbb4f03ddd56ed81f8da","scripts":{"test":"node --test --test-reporter=dot --test-reporter-destination=stdout test/*.test.ts","build":"tsgo -p tsconfig.build.json","clean":"shx rm -rf dist","prepublishOnly":"npm run clean && npm run build","build:native:win32":"node native/win32/build.mjs","build:native:darwin":"native/darwin/build.sh"},"_npmUser":{"name":"GitHub Actions","email":"npm-oidc-no-reply@github.com","trustedPublisher":{"id":"github","oidcConfigId":"oidc:6a738746-a660-4771-989e-da8d123b84a3"}},"repository":{"url":"git+https://github.com/guanwenpeng2001-bot/AOS-Agent.git","type":"git","directory":"packages/tui"},"_npmVersion":"11.5.1","description":"Terminal User Interface library with differential rendering for efficient text-based applications","directories":{},"_nodeVersion":"24.18.0","dependencies":{"marked":"18.0.5","get-east-asian-width":"1.6.0"},"_hasShrinkwrap":false,"devDependencies":{"chalk":"5.6.2","@xterm/headless":"5.5.0"},"_npmOperationalInternal":{"tmp":"tmp/tui_0.84.3_1786383947879_0.5606024341149709","host":"s3://npm-registry-packages-npm-production"}},"0.85.0":{"name":"@aos-agent/tui","version":"0.85.0","keywords":["tui","terminal","ui","text-editor","differential-rendering","typescript","cli"],"author":{"name":"AOS Agent"},"license":"MIT","_id":"@aos-agent/tui@0.85.0","maintainers":[{"name":"aosagent","email":"guanwenpeng2001@gmail.com"}],"homepage":"https://github.com/guanwenpeng2001-bot/AOS-Agent#readme","bugs":{"url":"https://github.com/guanwenpeng2001-bot/AOS-Agent/issues"},"dist":{"shasum":"e07cca860f09340b8ee5bbed9437160bcc4fd72d","tarball":"https://registry.npmjs.org/@aos-agent/tui/-/tui-0.85.0.tgz","fileCount":164,"integrity":"sha512-P6VfdFdZdn1seWk5Ff1xZ4/0AGwxZrrLPjjL0YaZPUOOp9v+eEY/+Kae0a3+2/EykgMX2mPDTbp6dPfNhIR6Cw==","signatures":[{"sig":"MEYCIQC89p1eA3Yjfhkn8hwLZw1xj3psXY2nlhbUprWIaN+lYQIhAN2OFm4MYKCjiAfWPlzaSpiYE4HeHwa6/JWejOhRkyJk","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"attestations":{"url":"https://registry.npmjs.org/-/npm/v1/attestations/@aos-agent%2ftui@0.85.0","provenance":{"predicateType":"https://slsa.dev/provenance/v1"}},"unpackedSize":2395432},"main":"dist/index.js","type":"module","types":"./dist/index.d.ts","engines":{"node":">=22.19.0"},"gitHead":"a305bd6d376b447cbdc0b92711a54e9778d24695","scripts":{"test":"node --test --test-reporter=dot --test-reporter-destination=stdout test/*.test.ts","build":"tsgo -p tsconfig.build.json","clean":"shx rm -rf dist","prepublishOnly":"npm run clean && npm run build","build:native:win32":"node native/win32/build.mjs","build:native:darwin":"native/darwin/build.sh"},"_npmUser":{"name":"GitHub Actions","email":"npm-oidc-no-reply@github.com","trustedPublisher":{"id":"github","oidcConfigId":"oidc:6a738746-a660-4771-989e-da8d123b84a3"}},"repository":{"url":"git+https://github.com/guanwenpeng2001-bot/AOS-Agent.git","type":"git","directory":"packages/tui"},"_npmVersion":"11.5.1","description":"Terminal User Interface library with differential rendering for efficient text-based applications","directories":{},"_nodeVersion":"24.19.0","dependencies":{"marked":"18.0.5","get-east-asian-width":"1.6.0"},"_hasShrinkwrap":false,"devDependencies":{"chalk":"5.6.2","@xterm/headless":"5.5.0"},"_npmOperationalInternal":{"tmp":"tmp/tui_0.85.0_1788326551769_0.869726588358618","host":"s3://npm-registry-packages-npm-production"}},"0.85.1":{"name":"@aos-agent/tui","version":"0.85.1","description":"Terminal User Interface library with differential rendering for efficient text-based applications","type":"module","main":"dist/index.js","scripts":{"clean":"shx rm -rf dist","build":"tsgo -p tsconfig.build.json","build:native:darwin":"native/darwin/build.sh","build:native:win32":"node native/win32/build.mjs","test":"node --test --test-reporter=dot --test-reporter-destination=stdout test/*.test.ts","prepublishOnly":"npm run clean && npm run build"},"keywords":["tui","terminal","ui","text-editor","differential-rendering","typescript","cli"],"author":{"name":"AOS Agent"},"license":"MIT","repository":{"type":"git","url":"git+https://github.com/guanwenpeng2001-bot/AOS-Agent.git","directory":"packages/tui"},"engines":{"node":">=22.19.0"},"types":"./dist/index.d.ts","dependencies":{"get-east-asian-width":"1.6.0","marked":"18.0.5"},"devDependencies":{"@xterm/headless":"5.5.0","chalk":"5.6.2"},"_id":"@aos-agent/tui@0.85.1","gitHead":"8fc01dea402bced66d545cf6febddcd944d8943b","bugs":{"url":"https://github.com/guanwenpeng2001-bot/AOS-Agent/issues"},"homepage":"https://github.com/guanwenpeng2001-bot/AOS-Agent#readme","_nodeVersion":"24.20.0","_npmVersion":"11.5.1","dist":{"integrity":"sha512-8/+5TjTjpaoxtt46aOTw88tkcv75sLxidODGiVL4EdnJyGIZlHgp7YHzUisbXhn8iDKca+k6TCXgMQuwjyt6lw==","shasum":"5fe7ef57fb31af04c07902b3d828a43120c99631","tarball":"https://registry.npmjs.org/@aos-agent/tui/-/tui-0.85.1.tgz","fileCount":164,"unpackedSize":2395432,"attestations":{"url":"https://registry.npmjs.org/-/npm/v1/attestations/@aos-agent%2ftui@0.85.1","provenance":{"predicateType":"https://slsa.dev/provenance/v1"}},"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEQCIFJxcpTxGR0raCd9VIk3BFSPAR7u0I1bIXsuEHKE/DJoAiBzHqi1teGrVO/vmgRTQxnRdIh5Pu2myryoItAOsJhCUw=="}]},"_npmUser":{"name":"GitHub Actions","email":"npm-oidc-no-reply@github.com","trustedPublisher":{"id":"github","oidcConfigId":"oidc:6a738746-a660-4771-989e-da8d123b84a3"}},"directories":{},"maintainers":[{"name":"aosagent","email":"guanwenpeng2001@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/tui_0.85.1_1788451919065_0.08933835033244986"},"_hasShrinkwrap":false}},"time":{"created":"2026-08-10T01:04:08.366Z","modified":"2026-09-03T16:11:59.619Z","0.84.2":"2026-08-10T01:04:08.649Z","0.84.3":"2026-08-10T17:45:48.041Z","0.85.0":"2026-09-02T05:22:31.923Z","0.85.1":"2026-09-03T16:11:59.221Z"},"bugs":{"url":"https://github.com/guanwenpeng2001-bot/AOS-Agent/issues"},"author":{"name":"AOS Agent"},"license":"MIT","homepage":"https://github.com/guanwenpeng2001-bot/AOS-Agent#readme","keywords":["tui","terminal","ui","text-editor","differential-rendering","typescript","cli"],"repository":{"type":"git","url":"git+https://github.com/guanwenpeng2001-bot/AOS-Agent.git","directory":"packages/tui"},"description":"Terminal User Interface library with differential rendering for efficient text-based applications","maintainers":[{"name":"aosagent","email":"guanwenpeng2001@gmail.com"}],"readme":"# @aos-agent/tui\n\nMinimal terminal UI framework with differential rendering and synchronized output for flicker-free interactive CLI applications.\n\n## Features\n\n- **Interchangeable Renderers**: Shared `TUI` interface with main-screen and alternate-screen implementations\n- **Differential Rendering**: Updates only changed lines or viewport rows\n- **Application-owned Scrolling**: Alternate-screen viewport supports mouse, trackpad, and keyboard navigation\n- **Synchronized Output**: Uses CSI 2026 for atomic screen updates (no flicker)\n- **Bracketed Paste Mode**: Handles large pastes correctly with markers for >10 line pastes\n- **Component-based**: Simple Component interface with render() method\n- **Theme Support**: Components accept theme interfaces for customizable styling\n- **Built-in Components**: Text, TruncatedText, Input, Editor, Markdown, Loader, SelectList, SettingsList, Spacer, Image, Box, Container, VStack, HStack, ScrollView\n- **Inline Images**: Renders images in terminals that support Kitty or iTerm2 graphics protocols\n- **Autocomplete Support**: File paths and slash commands\n\n## Quick Start\n\n```typescript\nimport { type TUI, Text, Editor, ProcessTerminal, TuiMainScreen, matchesKey } from \"@aos-agent/tui\";\n\n// Create terminal\nconst terminal = new ProcessTerminal();\n\n// Create the default main-screen renderer through the shared TUI interface\nconst tui: TUI = new TuiMainScreen(terminal);\n\n// Add components\ntui.addChild(new Text(\"Welcome to my app!\"));\n\nimport { defaultEditorTheme as editorTheme } from './test/test-themes.ts';\nconst editor = new Editor(tui, editorTheme);\neditor.onSubmit = (text) => {\n  console.log(\"Submitted:\", text);\n  tui.addChild(new Text(`You said: ${text}`));\n};\ntui.addChild(editor);\n\n// Focus the editor so it receives keyboard input\ntui.setFocus(editor);\n\n// In raw mode Ctrl+C doesn't send SIGINT — intercept it here to allow exit\ntui.addInputListener((data) => {\n  if (matchesKey(data, 'ctrl+c')) {\n    tui.stop();\n    process.exit(0);\n  }\n});\n\n// Start\ntui.start();\n```\n\n## Core API\n\n### TUI interface and renderers\n\n`TUI` is the shared interface for component management, focus, overlays, input, lifecycle, terminal queries, and rendering. Choose a concrete renderer only when constructing the application:\n\n- `TuiMainScreen` renders into the main terminal buffer and preserves terminal scrollback.\n- `TuiAltScreen` renders a fixed-height viewport in the alternate terminal buffer with application-owned scrolling. When stopped, it restores the main buffer and prints the complete final document.\n\n```typescript\nimport { type TUI, TuiAltScreen, TuiMainScreen } from \"@aos-agent/tui\";\n\nconst tui: TUI = new TuiMainScreen(terminal);\n// To use an application-owned viewport in the alternate terminal buffer instead:\n// const tui: TUI = new TuiAltScreen(terminal);\n\ntui.addChild(component);\ntui.removeChild(component);\ntui.start();\ntui.stop();\ntui.requestRender(); // Request a re-render\n\n// Global debug key handler (Shift+Ctrl+D)\ntui.onDebug = () => console.log(\"Debug triggered\");\n```\n\n### Alternate-screen viewport layouts\n\n`TuiAltScreen` can render an explicit terminal-height layout. `VStack` and `HStack` allocate constrained regions, while `ScrollView` owns scrolling for one region. These semantics are intentionally unavailable on `TuiMainScreen`, where the terminal owns scrollback.\n\n```typescript\nimport {\n  Container,\n  isViewportTUI,\n  ScrollView,\n  Text,\n  VStack,\n} from \"@aos-agent/tui\";\n\nconst transcript = new Container();\ntranscript.addChild(new Text(\"History\"));\n\nconst editorAndFooter = new VStack([\n  editor,\n  new Text(\"status\"),\n]);\n\nif (isViewportTUI(tui)) {\n  tui.setLayoutRoot(new VStack([\n    {\n      component: new ScrollView(transcript, {\n        follow: \"end\",\n        primary: true,\n        overscroll: \"chain\",\n      }),\n      basis: 0,\n      grow: 1,\n      minSize: 1,\n    },\n    {\n      component: editorAndFooter,\n      basis: \"auto\",\n      shrink: 1,\n      minSize: 1,\n    },\n  ]));\n}\n```\n\nStack entries support `basis`, `grow`, `shrink`, `minSize`, `maxSize`, and responsive `visible` callbacks. Mouse-wheel input targets the scroll view under the pointer and unused delta chains to outer scroll views by default. The primary scroll view receives the alternate-screen keyboard navigation actions and wheel input over non-scrollable regions. It can also jump between OSC 133 semantic prompt markers, matching common terminal prompt-navigation shortcuts.\n\nLayout geometry is rebuilt for each requested frame. Stateful components are retained, and their existing rendered-line caches remain effective. Calling `render(width)` directly on these layout components produces an unbounded document, which is also used when alt mode restores the main screen.\n\n### Overlays\n\nOverlays render components on top of existing content without replacing it. Useful for dialogs, menus, and modal UI.\n\n```typescript\n// Show overlay with default options (centered, max 80 cols)\nconst handle = tui.showOverlay(component);\n\n// Show overlay with custom positioning and sizing\n// Values can be numbers (absolute) or percentage strings (e.g., \"50%\")\nconst handle = tui.showOverlay(component, {\n  // Sizing\n  width: 60,              // Fixed width in columns\n  width: \"80%\",           // Width as percentage of terminal\n  minWidth: 40,           // Minimum width floor\n  maxHeight: 20,          // Maximum height in rows\n  maxHeight: \"50%\",       // Maximum height as percentage of terminal\n\n  // Anchor-based positioning (default: 'center')\n  anchor: 'bottom-right', // Position relative to anchor point\n  offsetX: 2,             // Horizontal offset from anchor\n  offsetY: -1,            // Vertical offset from anchor\n\n  // Percentage-based positioning (alternative to anchor)\n  row: \"25%\",             // Vertical position (0%=top, 100%=bottom)\n  col: \"50%\",             // Horizontal position (0%=left, 100%=right)\n\n  // Absolute positioning (overrides anchor/percent)\n  row: 5,                 // Exact row position\n  col: 10,                // Exact column position\n\n  // Margin from terminal edges\n  margin: 2,              // All sides\n  margin: { top: 1, right: 2, bottom: 1, left: 2 },\n\n  // Responsive visibility\n  visible: (termWidth, termHeight) => termWidth >= 100  // Hide on narrow terminals\n\n  // Focus behavior\n  nonCapturing: true       // Don't auto-focus when shown\n});\n\n// OverlayHandle methods\nhandle.hide();              // Permanently remove the overlay\nhandle.setHidden(true);     // Temporarily hide (can show again)\nhandle.setHidden(false);    // Show again after hiding\nhandle.isHidden();          // Check if temporarily hidden\nhandle.focus();             // Focus and bring to visual front\nhandle.unfocus();           // Release focus to normal fallback\nhandle.unfocus({ target: baseComponent }); // Release this overlay to a specific component\nhandle.unfocus({ target: null });   // Release this overlay and leave focus empty\nhandle.isFocused();         // Check if overlay has focus\n\nhandle.unfocus();\n// Overlay loses focus; TUI falls back to another visible capturing overlay or the previous focus target.\n\nhandle.unfocus({ target: null });\n// Overlay loses focus; no component receives input until focus is set again.\n\n// A focused visible overlay reclaims keyboard input after temporary replacement UI\n// releases focus. If you want a specific component to receive input while overlays remain\n// visible, call handle.unfocus({ target: component }).\n\n// Hide topmost overlay\ntui.hideOverlay();\n\n// Check if any visible overlay is active\ntui.hasOverlay();\n```\n\n**Anchor values**: `'center'`, `'top-left'`, `'top-right'`, `'bottom-left'`, `'bottom-right'`, `'top-center'`, `'bottom-center'`, `'left-center'`, `'right-center'`\n\n**Resolution order**:\n1. `minWidth` is applied as a floor after width calculation\n2. For position: absolute `row`/`col` > percentage `row`/`col` > `anchor`\n3. `margin` clamps final position to stay within terminal bounds\n4. `visible` callback controls whether overlay renders (called each frame)\n\n### Component Interface\n\nAll components implement:\n\n```typescript\ninterface Component {\n  render(width: number): string[];\n  handleInput?(data: string): void;\n  invalidate?(): void;\n}\n```\n\n| Method | Description |\n|--------|-------------|\n| `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. |\n| `handleInput?(data)` | Called when the component has focus and receives keyboard input. The `data` string contains raw terminal input (may include ANSI escape sequences). |\n| `invalidate?()` | Called to clear any cached render state. Components should re-render from scratch on the next `render()` call. |\n\nThe 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.\n\n### Focusable Interface (IME Support)\n\nComponents that display a text cursor and need IME (Input Method Editor) support should implement the `Focusable` interface:\n\n```typescript\nimport { CURSOR_MARKER, type Component, type Focusable } from \"@aos-agent/tui\";\n\nclass MyInput implements Component, Focusable {\n  focused: boolean = false;  // Set by TUI when focus changes\n  \n  render(width: number): string[] {\n    const marker = this.focused ? CURSOR_MARKER : \"\";\n    // Emit marker right before the fake cursor\n    return [`> ${beforeCursor}${marker}\\x1b[7m${atCursor}\\x1b[27m${afterCursor}`];\n  }\n}\n```\n\nWhen a `Focusable` component has focus, TUI:\n1. Sets `focused = true` on the component\n2. Scans rendered output for `CURSOR_MARKER` (a zero-width APC escape sequence)\n3. Positions the hardware terminal cursor at that location\n4. Shows the hardware cursor only when `showHardwareCursor` is enabled\n\nThe cursor remains hidden by default. This keeps the fake cursor rendering, while still positioning the hardware cursor for terminals that track IME candidate windows with hidden cursors. Some terminals require a visible hardware cursor for IME positioning; enable it with the renderer constructor's `showHardwareCursor` argument, `setShowHardwareCursor(true)`, or `AOS_AGENT_HARDWARE_CURSOR=1`. The `Editor` and `Input` built-in components already implement this interface.\n\n**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:\n\n```typescript\nimport { Container, type Focusable, Input } from \"@aos-agent/tui\";\n\nclass SearchDialog extends Container implements Focusable {\n  private searchInput: Input;\n\n  // Propagate focus to child input for IME cursor positioning\n  private _focused = false;\n  get focused(): boolean { return this._focused; }\n  set focused(value: boolean) {\n    this._focused = value;\n    this.searchInput.focused = value;\n  }\n\n  constructor() {\n    super();\n    this.searchInput = new Input();\n    this.addChild(this.searchInput);\n  }\n}\n```\n\nWithout this propagation, typing with an IME (Chinese, Japanese, Korean, etc.) will show the candidate window in the wrong position.\n\n## Built-in Components\n\n### Container\n\nGroups child components.\n\n```typescript\nconst container = new Container();\ncontainer.addChild(component);\ncontainer.removeChild(component);\n```\n\n### Box\n\nContainer that applies padding and background color to all children.\n\n```typescript\nconst box = new Box(\n  1,                              // paddingX (default: 1)\n  1,                              // paddingY (default: 1)\n  (text) => chalk.bgGray(text)   // optional background function\n);\nbox.addChild(new Text(\"Content\"));\nbox.setBgFn((text) => chalk.bgBlue(text));  // Change background dynamically\n```\n\n### Text\n\nDisplays multi-line text with word wrapping and padding.\n\n```typescript\nconst text = new Text(\n  \"Hello World\",                  // text content\n  1,                              // paddingX (default: 1)\n  1,                              // paddingY (default: 1)\n  (text) => chalk.bgGray(text)   // optional background function\n);\ntext.setText(\"Updated text\");\ntext.setCustomBgFn((text) => chalk.bgBlue(text));\n```\n\n### TruncatedText\n\nSingle-line text that truncates to fit viewport width. Useful for status lines and headers.\n\n```typescript\nconst truncated = new TruncatedText(\n  \"This is a very long line that will be truncated...\",\n  0,  // paddingX (default: 0)\n  0   // paddingY (default: 0)\n);\n```\n\n### Input\n\nSingle-line text input with horizontal scrolling.\n\n```typescript\nconst input = new Input();\ninput.onSubmit = (value) => console.log(value);\ninput.setValue(\"initial\");\ninput.getValue();\n```\n\n**Key Bindings:**\n- `Enter` - Submit\n- `Ctrl+A` / `Ctrl+E` - Line start/end\n- `Ctrl+W` or `Alt+Backspace` - Delete word backwards\n- `Ctrl+U` - Delete to start of line\n- `Ctrl+K` - Delete to end of line\n- `Ctrl+Left` / `Ctrl+Right` - Word navigation\n- `Alt+Left` / `Alt+Right` - Word navigation\n- Arrow keys, Backspace, Delete work as expected\n\n### Editor\n\nMulti-line text editor with autocomplete, file completion, paste handling, and vertical scrolling when content exceeds terminal height.\n\n```typescript\ninterface EditorTheme {\n  borderColor: (str: string) => string;\n  selectList: SelectListTheme;\n}\n\ninterface EditorOptions {\n  paddingX?: number;  // Horizontal padding (default: 0)\n}\n\nconst editor = new Editor(tui, theme, options?);  // tui is required for height-aware scrolling\neditor.onSubmit = (text) => console.log(text);\neditor.onChange = (text) => console.log(\"Changed:\", text);\neditor.disableSubmit = true; // Disable submit temporarily\neditor.setAutocompleteProvider(provider);\neditor.borderColor = (s) => chalk.blue(s); // Change border dynamically\neditor.setPaddingX(1); // Update horizontal padding dynamically\neditor.getPaddingX();  // Get current padding\n```\n\n**Features:**\n- Multi-line editing with word wrap\n- Slash command autocomplete (type `/`)\n- File path autocomplete (press `Tab`)\n- Large paste handling (>10 lines creates `[paste #1 +50 lines]` marker)\n- Horizontal lines above/below editor\n- Fake cursor rendering (hidden real cursor)\n\n**Key Bindings:**\n- `Enter` - Submit\n- `Shift+Enter`, `Ctrl+Enter`, or `Alt+Enter` - New line (terminal-dependent, Alt+Enter most reliable)\n- `Tab` - Autocomplete\n- `Ctrl+K` - Delete to end of line\n- `Ctrl+U` - Delete to start of line\n- `Ctrl+W` or `Alt+Backspace` - Delete word backwards\n- `Alt+D` or `Alt+Delete` - Delete word forwards\n- `Ctrl+A` / `Ctrl+E` - Line start/end\n- `Ctrl+]` - Jump forward to character (awaits next keypress, then moves cursor to first occurrence)\n- `Ctrl+Alt+]` - Jump backward to character\n- Arrow keys, Backspace, Delete work as expected\n\n### Markdown\n\nRenders markdown with syntax highlighting and theming support.\n\n```typescript\ninterface MarkdownTheme {\n  heading: (text: string) => string;\n  link: (text: string) => string;\n  linkUrl: (text: string) => string;\n  code: (text: string) => string;\n  codeBlock: (text: string) => string;\n  codeBlockBorder: (text: string) => string;\n  quote: (text: string) => string;\n  quoteBorder: (text: string) => string;\n  hr: (text: string) => string;\n  listBullet: (text: string) => string;\n  bold: (text: string) => string;\n  italic: (text: string) => string;\n  strikethrough: (text: string) => string;\n  underline: (text: string) => string;\n  highlightCode?: (code: string, lang?: string) => string[];\n}\n\ninterface DefaultTextStyle {\n  color?: (text: string) => string;\n  bgColor?: (text: string) => string;\n  bold?: boolean;\n  italic?: boolean;\n  strikethrough?: boolean;\n  underline?: boolean;\n}\n\nconst md = new Markdown(\n  \"# Hello\\n\\nSome **bold** text\",\n  1,              // paddingX\n  1,              // paddingY\n  theme,          // MarkdownTheme\n  defaultStyle    // optional DefaultTextStyle\n);\nmd.setText(\"Updated markdown\");\n```\n\n**Features:**\n- Headings, bold, italic, code blocks, lists, links, blockquotes\n- HTML tags rendered as plain text\n- Optional syntax highlighting via `highlightCode`\n- Padding support\n- Render caching for performance\n\n### Loader\n\nAnimated loading spinner.\n\n```typescript\nconst loader = new Loader(\n  tui,                              // TUI instance for render updates\n  (s) => chalk.cyan(s),            // spinner color function\n  (s) => chalk.gray(s),            // message color function\n  \"Loading...\"                      // message (default: \"Loading...\")\n);\nloader.start();\nloader.setMessage(\"Still loading...\");\nloader.stop();\n```\n\n### CancellableLoader\n\nExtends Loader with Escape key handling and an AbortSignal for cancelling async operations.\n\n```typescript\nconst loader = new CancellableLoader(\n  tui,                              // TUI instance for render updates\n  (s) => chalk.cyan(s),            // spinner color function\n  (s) => chalk.gray(s),            // message color function\n  \"Working...\"                      // message\n);\nloader.onAbort = () => done(null); // Called when user presses Escape\ndoAsyncWork(loader.signal).then(done);\n```\n\n**Properties:**\n- `signal: AbortSignal` - Aborted when user presses Escape\n- `aborted: boolean` - Whether the loader was aborted\n- `onAbort?: () => void` - Callback when user presses Escape\n\n### SelectList\n\nInteractive selection list with keyboard navigation.\n\n```typescript\ninterface SelectItem {\n  value: string;\n  label: string;\n  description?: string;\n}\n\ninterface SelectListTheme {\n  selectedPrefix: (text: string) => string;\n  selectedText: (text: string) => string;\n  description: (text: string) => string;\n  scrollInfo: (text: string) => string;\n  noMatch: (text: string) => string;\n}\n\nconst list = new SelectList(\n  [\n    { value: \"opt1\", label: \"Option 1\", description: \"First option\" },\n    { value: \"opt2\", label: \"Option 2\", description: \"Second option\" },\n  ],\n  5,      // maxVisible\n  theme   // SelectListTheme\n);\n\nlist.onSelect = (item) => console.log(\"Selected:\", item);\nlist.onCancel = () => console.log(\"Cancelled\");\nlist.onSelectionChange = (item) => console.log(\"Highlighted:\", item);\nlist.setFilter(\"opt\"); // Filter items\n```\n\n**Controls:**\n- Arrow keys: Navigate\n- Enter: Select\n- Escape: Cancel\n\n### SettingsList\n\nSettings panel with value cycling and submenus.\n\n```typescript\ninterface SettingItem {\n  id: string;\n  label: string;\n  description?: string;\n  currentValue: string;\n  values?: string[];  // If provided, Enter/Space cycles through these\n  submenu?: (currentValue: string, done: (selectedValue?: string) => void) => Component;\n}\n\ninterface SettingsListTheme {\n  label: (text: string, selected: boolean) => string;\n  value: (text: string, selected: boolean) => string;\n  description: (text: string) => string;\n  cursor: string;\n  hint: (text: string) => string;\n}\n\nconst settings = new SettingsList(\n  [\n    { id: \"theme\", label: \"Theme\", currentValue: \"dark\", values: [\"dark\", \"light\"] },\n    { id: \"model\", label: \"Model\", currentValue: \"gpt-4\", submenu: (val, done) => modelSelector },\n  ],\n  10,      // maxVisible\n  theme,   // SettingsListTheme\n  (id, newValue) => console.log(`${id} changed to ${newValue}`),\n  () => console.log(\"Cancelled\")\n);\nsettings.updateValue(\"theme\", \"light\");\n```\n\n**Controls:**\n- Arrow keys: Navigate\n- Enter/Space: Activate (cycle value or open submenu)\n- Escape: Cancel\n\n### Spacer\n\nEmpty lines for vertical spacing.\n\n```typescript\nconst spacer = new Spacer(2); // 2 empty lines (default: 1)\n```\n\n### Image\n\nRenders images inline for terminals that support the Kitty graphics protocol (Kitty, Ghostty, WezTerm) or iTerm2 inline images. Falls back to a text placeholder on unsupported terminals.\n\n```typescript\ninterface ImageTheme {\n  fallbackColor: (str: string) => string;\n}\n\ninterface ImageOptions {\n  maxWidthCells?: number;\n  maxHeightCells?: number;\n  filename?: string;\n}\n\nconst image = new Image(\n  base64Data,       // base64-encoded image data\n  \"image/png\",      // MIME type\n  theme,            // ImageTheme\n  options           // optional ImageOptions\n);\ntui.addChild(image);\n```\n\nSupported formats: PNG, JPEG, GIF, WebP. Dimensions are parsed from the image headers automatically.\n\n#### Alternate-screen image compatibility\n\n`TuiAltScreen` supports inline images and partial viewport cropping in terminals that implement the Kitty graphics protocol, including Kitty and Ghostty. iTerm2's inline-image protocol does not provide operations to delete an existing placement or crop its source while scrolling. To prevent stale images from remaining over repainted content, `TuiAltScreen` renders image components as text placeholders in iTerm2. `TuiMainScreen` continues to render iTerm2 inline images normally.\n\n## Autocomplete\n\n### CombinedAutocompleteProvider\n\nSupports both slash commands and file paths.\n\n```typescript\nimport { CombinedAutocompleteProvider } from \"@aos-agent/tui\";\n\nconst provider = new CombinedAutocompleteProvider(\n  [\n    { name: \"help\", description: \"Show help\" },\n    { name: \"clear\", description: \"Clear screen\" },\n    { name: \"delete\", description: \"Delete last message\" },\n  ],\n  process.cwd() // base path for file completion\n);\n\neditor.setAutocompleteProvider(provider);\n```\n\n**Features:**\n- Type `/` to see slash commands\n- Press `Tab` for file path completion\n- Works with `~/`, `./`, `../`, and `@` prefix\n- Filters to attachable files for `@` prefix\n\n## Key Detection\n\nUse `matchesKey()` with the `Key` helper for detecting keyboard input (supports Kitty keyboard protocol):\n\n```typescript\nimport { matchesKey, Key } from \"@aos-agent/tui\";\n\nif (matchesKey(data, Key.ctrl(\"c\"))) {\n  process.exit(0);\n}\n\nif (matchesKey(data, Key.enter)) {\n  submit();\n} else if (matchesKey(data, Key.escape)) {\n  cancel();\n} else if (matchesKey(data, Key.up)) {\n  moveUp();\n}\n```\n\n**Key identifiers** (use `Key.*` for autocomplete, or string literals):\n- Basic keys: `Key.enter`, `Key.escape`, `Key.tab`, `Key.space`, `Key.backspace`, `Key.delete`, `Key.home`, `Key.end`\n- Arrow keys: `Key.up`, `Key.down`, `Key.left`, `Key.right`\n- With modifiers: `Key.ctrl(\"c\")`, `Key.shift(\"tab\")`, `Key.alt(\"left\")`, `Key.ctrlShift(\"p\")`\n- String format also works: `\"enter\"`, `\"ctrl+c\"`, `\"shift+tab\"`, `\"ctrl+shift+p\"`\n\n## Rendering modes\n\n`TuiMainScreen` uses three rendering strategies:\n\n1. **First Render**: Output all lines without clearing scrollback\n2. **Width Changed or Change Above Viewport**: Clear screen and fully re-render\n3. **Normal Update**: Move the cursor to the first changed line, clear to the end, and render changed lines\n\n`TuiAltScreen` owns a terminal-height viewport. Without an explicit layout root it preserves the legacy single-document scrolling behavior. With `setLayoutRoot()`, `VStack`, `HStack`, and nested `ScrollView` components can reserve fixed regions and independently scroll constrained regions. It updates changed viewport rows in place, follows streaming output while at the bottom, and preserves a manually selected scroll position while content grows. Mouse-wheel and configurable keyboard navigation scroll without modifying terminal scrollback, including jumps between OSC 133 semantic prompt markers. Clicking an OSC 8 hyperlink opens it with the configured URL handler. Dragging with the primary mouse button selects text and copies it to the clipboard with OSC 52; holding the drag at a scroll view's top or bottom edge auto-scrolls and extends the selection into off-screen content. Kitty images support vertical viewport cropping; iTerm2 inline images fall back to text because the iTerm2 protocol cannot delete or crop placements during viewport repainting.\n\nBoth renderers wrap updates in **synchronized output** (`\\x1b[?2026h` ... `\\x1b[?2026l`) for atomic, flicker-free rendering.\n\n## Terminal Interface\n\nThe TUI works with any object implementing the `Terminal` interface:\n\n```typescript\ninterface Terminal {\n  start(onInput: (data: string) => void, onResize: () => void): void;\n  stop(): void;\n  write(data: string): void;\n  get columns(): number;\n  get rows(): number;\n  moveBy(lines: number): void;\n  hideCursor(): void;\n  showCursor(): void;\n  clearLine(): void;\n  clearFromCursor(): void;\n  clearScreen(): void;\n}\n```\n\n**Built-in implementations:**\n- `ProcessTerminal` - Uses `process.stdin/stdout`\n- `VirtualTerminal` - For testing (uses `@xterm/headless`)\n\n## Utilities\n\n```typescript\nimport { visibleWidth, truncateToWidth, wrapTextWithAnsi } from \"@aos-agent/tui\";\n\n// Get visible width of string (ignoring ANSI codes)\nconst width = visibleWidth(\"\\x1b[31mHello\\x1b[0m\"); // 5\n\n// Truncate string to width (preserving ANSI codes, adds ellipsis)\nconst truncated = truncateToWidth(\"Hello World\", 8); // \"Hello...\"\n\n// Truncate without ellipsis\nconst truncatedNoEllipsis = truncateToWidth(\"Hello World\", 8, \"\"); // \"Hello Wo\"\n\n// Wrap text to width (preserving ANSI codes across line breaks)\nconst lines = wrapTextWithAnsi(\"This is a long line that needs wrapping\", 20);\n// [\"This is a long line\", \"that needs wrapping\"]\n```\n\n## Creating Custom Components\n\nWhen 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.\n\n### Handling Input\n\nUse `matchesKey()` with the `Key` helper for keyboard input:\n\n```typescript\nimport { matchesKey, Key, truncateToWidth } from \"@aos-agent/tui\";\nimport type { Component } from \"@aos-agent/tui\";\n\nclass MyInteractiveComponent implements Component {\n  private selectedIndex = 0;\n  private items = [\"Option 1\", \"Option 2\", \"Option 3\"];\n  \n  public onSelect?: (index: number) => void;\n  public onCancel?: () => void;\n\n  handleInput(data: string): void {\n    if (matchesKey(data, Key.up)) {\n      this.selectedIndex = Math.max(0, this.selectedIndex - 1);\n    } else if (matchesKey(data, Key.down)) {\n      this.selectedIndex = Math.min(this.items.length - 1, this.selectedIndex + 1);\n    } else if (matchesKey(data, Key.enter)) {\n      this.onSelect?.(this.selectedIndex);\n    } else if (matchesKey(data, Key.escape) || matchesKey(data, Key.ctrl(\"c\"))) {\n      this.onCancel?.();\n    }\n  }\n\n  render(width: number): string[] {\n    return this.items.map((item, i) => {\n      const prefix = i === this.selectedIndex ? \"> \" : \"  \";\n      return truncateToWidth(prefix + item, width);\n    });\n  }\n}\n```\n\n### Handling Line Width\n\nUse the provided utilities to ensure lines fit:\n\n```typescript\nimport { visibleWidth, truncateToWidth } from \"@aos-agent/tui\";\nimport type { Component } from \"@aos-agent/tui\";\n\nclass MyComponent implements Component {\n  private text: string;\n\n  constructor(text: string) {\n    this.text = text;\n  }\n\n  render(width: number): string[] {\n    // Option 1: Truncate long lines\n    return [truncateToWidth(this.text, width)];\n\n    // Option 2: Check and pad to exact width\n    const line = this.text;\n    const visible = visibleWidth(line);\n    if (visible > width) {\n      return [truncateToWidth(line, width)];\n    }\n    // Pad to exact width (optional, for backgrounds)\n    return [line + \" \".repeat(width - visible)];\n  }\n}\n```\n\n### ANSI Code Considerations\n\nBoth `visibleWidth()` and `truncateToWidth()` correctly handle ANSI escape codes:\n\n- `visibleWidth()` ignores ANSI codes when calculating width\n- `truncateToWidth()` preserves ANSI codes and properly closes them when truncating\n\n```typescript\nimport chalk from \"chalk\";\n\nconst styled = chalk.red(\"Hello\") + \" \" + chalk.blue(\"World\");\nconst width = visibleWidth(styled); // 11 (not counting ANSI codes)\nconst truncated = truncateToWidth(styled, 8); // Red \"Hello\" + \" W...\" with proper reset\n```\n\n### Caching\n\nFor performance, components should cache their rendered output and only re-render when necessary:\n\n```typescript\nclass CachedComponent implements Component {\n  private text: string;\n  private cachedWidth?: number;\n  private cachedLines?: string[];\n\n  render(width: number): string[] {\n    if (this.cachedLines && this.cachedWidth === width) {\n      return this.cachedLines;\n    }\n\n    const lines = [truncateToWidth(this.text, width)];\n\n    this.cachedWidth = width;\n    this.cachedLines = lines;\n    return lines;\n  }\n\n  invalidate(): void {\n    this.cachedWidth = undefined;\n    this.cachedLines = undefined;\n  }\n}\n```\n\n## Example\n\nSee `test/chat-simple.ts` for a complete chat interface example with:\n- Markdown messages with custom background colors\n- Loading spinner during responses\n- Editor with autocomplete and slash commands\n- Spacers between messages\n\nRun it:\n```bash\nnpx tsx test/chat-simple.ts\n```\n\n## Development\n\n```bash\n# Install dependencies (from monorepo root)\nnpm install\n\n# Run type checking\nnpm run check\n\n# Run the demo\nnpx tsx test/chat-simple.ts\n```\n\n### Debug logging\n\nSet `AOS_AGENT_TUI_WRITE_LOG` to capture the raw ANSI stream written to stdout.\n\n```bash\nAOS_AGENT_TUI_WRITE_LOG=/tmp/tui-ansi.log npx tsx test/chat-simple.ts\n```\n","readmeFilename":"README.md"}