Skip to main content

PTY-based terminal emulator with web backend for running TUI applications via HTTP/WebSocket APIs

Project description

Term Wrapper

CI

A full-featured terminal emulator with web backend that can run any TUI (Text User Interface) application and control it via HTTP/WebSocket APIs.

Features

  • PTY-based Terminal Emulation: Full pseudo-terminal support for running terminal applications
  • FastAPI Backend: RESTful API and WebSocket endpoints for terminal control
  • Session Management: Create, manage, and control multiple terminal sessions
  • CLI Subcommands: Scriptable terminal control from bash/shell without writing Python
  • Python Client Library: High-level primitives (wait_for_text, wait_for_quiet, get_text)
  • Comprehensive Tests: 118 tests covering unit, integration, and e2e scenarios

What's Supported

โœ… Fully Working

  • Simple commands: ls, cat, echo, shell scripts
  • Interactive programs: Python REPL, bash, interactive shells
  • Complex TUI apps: vim, less, nano (tested with web frontend)
  • AI CLI tools: claude CLI (tested with both print and interactive modes)
  • Full-screen apps: Full support via xterm.js web frontend
  • ANSI colors & formatting: Complete support for escape sequences
  • Terminal resize: Dynamic window resizing with SIGWINCH
  • Multiple sessions: Concurrent terminal sessions with session management

๐ŸŒ Optional Web Frontend

The included web frontend (frontend/) serves as a universal web mirror for any TUI application:

  • Access any terminal app through your browser with full rendering
  • Built with xterm.js for complete ANSI escape sequence support
  • Mobile-friendly interface for running TUI apps on phones/tablets
  • Not required - the REST/CLI API works standalone for programmatic control

Architecture

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚   CLI Client    โ”‚ โ† Python client for interactive control
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
         โ”‚ HTTP/WebSocket
         โ†“
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  FastAPI Server โ”‚ โ† Web backend with REST + WebSocket
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
         โ”‚
         โ†“
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚ Session Manager โ”‚ โ† Manages multiple terminal sessions
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
         โ”‚
         โ†“
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚ PTY Terminal    โ”‚ โ† Pseudo-terminal for running TUI apps
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
         โ”‚
         โ†“
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚   TUI App       โ”‚ โ† Any terminal application (vim, htop, etc.)
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Installation

From PyPI (Recommended for Users)

pip install term-wrapper

This installs the package and makes the term-wrapper CLI command available:

term-wrapper --help
term-wrapper create htop

From Source (For Development)

git clone https://github.com/rom1504/term-wrapper.git
cd term-wrapper
uv sync

When developing with uv, prefix commands with uv run:

uv run term-wrapper --help
uv run term-wrapper create htop

Quick Start

1. Start the Server

uv run python main.py

Server will start on http://localhost:8000

3. Run a TUI App

Option A: Using CLI Subcommands (Recommended)

# Create a session
SESSION=$(term-wrapper create bash -c "cd /tmp && claude" | python3 -c "import sys, json; print(json.load(sys.stdin)['session_id'])")

# Wait for text to appear
term-wrapper wait-text $SESSION "Welcome" --timeout 10

# Send input (supports \n, \r, \t, \x1b escape sequences)
term-wrapper send $SESSION "create hello.py\r"

# Get clean text output (ANSI codes stripped)
term-wrapper get-text $SESSION

# Wait for output to stabilize
term-wrapper wait-quiet $SESSION --duration 2

# Delete session
term-wrapper delete $SESSION

See all available subcommands:

term-wrapper --help

Note: In development with uv, prefix commands with uv run, e.g., `uv run term-wrapper --help


#### Option B: Using Python Client Library

```python
from term_wrapper.cli import TerminalClient

client = TerminalClient()
session_id = client.create_session(command=["bash"], rows=40, cols=120)

# High-level primitives
client.wait_for_text(session_id, "Welcome", timeout=10)
client.write_input(session_id, "ls -la\r")
text = client.get_text(session_id)  # Clean text, ANSI stripped
client.wait_for_quiet(session_id, duration=2)  # Wait for stability

client.delete_session(session_id)
client.close()

Option C: Using HTTP API Directly

# Create a session
curl -X POST http://localhost:8000/sessions \
  -H "Content-Type: application/json" \
  -d '{"command": ["python3", "examples/simple_tui.py"], "rows": 24, "cols": 80}'

# Returns: {"session_id": "xxx-xxx-xxx"}

# Get output
curl http://localhost:8000/sessions/{session_id}/output

# Send input
curl -X POST http://localhost:8000/sessions/{session_id}/input \
  -H "Content-Type: application/json" \
  -d '{"data": "+"}'

# Delete session
curl -X DELETE http://localhost:8000/sessions/{session_id}

CLI Subcommands

The term-wrapper CLI command is installed automatically when you install the package via pip. It provides scriptable terminal control without writing Python code. All commands output JSON for easy parsing.

Installation: The CLI entry point is defined in pyproject.toml as:

[project.scripts]
term-wrapper = "term_wrapper.cli:sync_main"

After pip install term-wrapper, the term-wrapper command will be available in your PATH. During development with uv, use uv run term-wrapper.

Available Subcommands

# Session Management
term-wrapper create [--rows N] [--cols N] [--env JSON] COMMAND...
term-wrapper list
term-wrapper info SESSION_ID
term-wrapper delete SESSION_ID

# Input/Output
term-wrapper send SESSION_ID TEXT           # Supports \n, \r, \t, \x1b
term-wrapper get-output SESSION_ID          # Raw output with ANSI codes
term-wrapper get-text SESSION_ID            # Clean text (ANSI stripped)
term-wrapper get-screen SESSION_ID          # Parsed 2D screen buffer

# Waiting Primitives
term-wrapper wait-text SESSION_ID TEXT [--timeout SECS]
term-wrapper wait-quiet SESSION_ID [--duration SECS] [--timeout SECS]

# Interactive
term-wrapper attach SESSION_ID              # WebSocket interactive mode

Shell Script Example

#!/bin/bash
# Automate vim file editing

SESSION=$(uv run python -m term_wrapper.cli create vim myfile.txt | \
          python3 -c "import sys, json; print(json.load(sys.stdin)['session_id'])")

# Enter insert mode
uv run python -m term_wrapper.cli send $SESSION "i"
sleep 0.3

# Type content
uv run python -m term_wrapper.cli send $SESSION "Hello World\nLine 2"
sleep 0.5

# Save and quit (ESC + :wq)
uv run python -m term_wrapper.cli send $SESSION "\x1b"
uv run python -m term_wrapper.cli send $SESSION ":wq\r"
sleep 0.5

# Cleanup
uv run python -m term_wrapper.cli delete $SESSION

See examples/ directory for more examples with vim, htop, and Claude Code.

Python Client Library

The TerminalClient class provides high-level primitives for terminal control:

from term_wrapper.cli import TerminalClient

client = TerminalClient(base_url="http://localhost:8000")

# Session management
session_id = client.create_session(command=["bash"], rows=40, cols=120)
sessions = client.list_sessions()
info = client.get_session_info(session_id)
client.delete_session(session_id)

# Input/Output
client.write_input(session_id, "ls -la\r")
output = client.get_output(session_id, clear=True)
text = client.get_text(session_id, strip_ansi_codes=True)
screen = client.get_screen(session_id)  # 2D screen buffer

# Waiting primitives
client.wait_for_text(session_id, "username:", timeout=10)
client.wait_for_condition(session_id, lambda text: "done" in text, timeout=30)
client.wait_for_quiet(session_id, duration=2.0, timeout=30)

# Incremental reading
new_lines = client.get_new_lines(session_id)
client.mark_read(session_id)

client.close()

API Reference

REST Endpoints

  • POST /sessions - Create a new terminal session
  • GET /sessions - List all active sessions
  • GET /sessions/{id} - Get session information
  • DELETE /sessions/{id} - Delete a session
  • POST /sessions/{id}/input - Send input to terminal
  • POST /sessions/{id}/resize - Resize terminal window
  • GET /sessions/{id}/output - Get raw terminal output
  • GET /sessions/{id}/screen - Get parsed 2D screen buffer (clean text)

WebSocket Endpoint

  • WS /sessions/{id}/ws - Real-time bidirectional terminal I/O

Testing

Run all tests:

uv run pytest tests/ -v

Run specific test suites:

# Unit tests
uv run pytest tests/test_terminal.py tests/test_api.py -v

# End-to-end tests
uv run pytest tests/test_e2e.py -v

# Integration tests with TUI apps
uv run pytest tests/test_ink_integration.py -v

# Vim tests
uv run pytest tests/test_vim.py -v

Application Reports

We've tested various TUI applications with detailed reports:

Application Status Report Tests
vim โœ… Fully Functional reports/vim_report.md tests/test_vim.py
htop โœ… Fully Functional reports/htop_report.md tests/test_htop.py
Claude CLI โœ… Fully Functional reports/claude_report.md tests/test_claude.py

Each report includes:

  • Test methodology and results
  • Usage examples (HTTP & WebSocket)
  • Technical details (escape sequences, commands)
  • Performance metrics
  • Best practices

Want to add a new application? See reports/TESTING_GUIDE.md for a comprehensive step-by-step guide on testing and documenting new TUI applications.

Claude Code Skill

Want to use term-wrapper with Claude Code? Check out the Term Wrapper skill!

The skill enables Claude to control any terminal application programmatically. See skill/SKILL.md for complete instructions on using term-wrapper with CLI commands, Python, or HTTP APIs.

Example TUI Apps

Interactive htop Demo (examples/htop_demo.py)

Demonstrates full interaction with htop system monitor:

uv run python examples/htop_demo.py

Features:

  • Navigate process list with arrow keys
  • Toggle tree view
  • Change sort order
  • Interactive command mode
  • Live system monitoring through the API

Python TUI App (examples/simple_tui.py)

A simple counter application demonstrating:

  • Terminal control codes
  • Raw mode input handling
  • Interactive key bindings

Controls:

  • + : Increment counter
  • - : Decrement counter
  • r : Reset counter
  • q : Quit

Project Structure

term_wrapper/
โ”œโ”€โ”€ term_wrapper/      # Main package
โ”‚   โ”œโ”€โ”€ terminal.py        # PTY-based terminal emulator
โ”‚   โ”œโ”€โ”€ session_manager.py # Session management
โ”‚   โ”œโ”€โ”€ api.py            # FastAPI backend
โ”‚   โ””โ”€โ”€ cli.py            # CLI client
โ”œโ”€โ”€ tests/                 # Test suite
โ”‚   โ”œโ”€โ”€ test_terminal.py   # Terminal emulator tests
โ”‚   โ”œโ”€โ”€ test_api.py        # API tests
โ”‚   โ”œโ”€โ”€ test_e2e.py       # End-to-end tests
โ”‚   โ””โ”€โ”€ test_ink_integration.py # TUI app tests
โ”œโ”€โ”€ examples/             # Example applications
โ”‚   โ”œโ”€โ”€ simple_example.py # Simple HTTP API usage
โ”‚   โ”œโ”€โ”€ vim_example.py    # Vim automation example
โ”‚   โ”œโ”€โ”€ htop_demo.py      # Interactive htop demonstration
โ”‚   โ””โ”€โ”€ simple_tui.py     # Python TUI demo
โ”œโ”€โ”€ skill/                # Claude Code skill
โ”‚   โ””โ”€โ”€ SKILL.md          # Term Wrapper skill for AI agents
โ”œโ”€โ”€ frontend/             # Web frontend with xterm.js
โ”œโ”€โ”€ docs/                 # Documentation
โ”œโ”€โ”€ scripts/              # Utility scripts
โ”œโ”€โ”€ main.py              # Server entry point
โ””โ”€โ”€ pyproject.toml       # Project configuration

Development

Built with:

  • uv - Fast Python package manager
  • FastAPI - Modern web framework
  • uvicorn - ASGI server
  • pytest - Testing framework
  • websockets - WebSocket support

License

ISC

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

term_wrapper-0.2.1.tar.gz (88.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

term_wrapper-0.2.1-py3-none-any.whl (19.9 kB view details)

Uploaded Python 3

File details

Details for the file term_wrapper-0.2.1.tar.gz.

File metadata

  • Download URL: term_wrapper-0.2.1.tar.gz
  • Upload date:
  • Size: 88.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.12

File hashes

Hashes for term_wrapper-0.2.1.tar.gz
Algorithm Hash digest
SHA256 7cb083f781d776f9b03a284e08b43ce77c0b9e08a1c7bece8a3f76efce5b5641
MD5 5d457b6d7d3f4baa04ff68dee7fdbb84
BLAKE2b-256 ad8918b3390c0bfd94b8a8ab7936aac0406d5f7eccef45741da5da40ce319f17

See more details on using hashes here.

File details

Details for the file term_wrapper-0.2.1-py3-none-any.whl.

File metadata

  • Download URL: term_wrapper-0.2.1-py3-none-any.whl
  • Upload date:
  • Size: 19.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.12

File hashes

Hashes for term_wrapper-0.2.1-py3-none-any.whl
Algorithm Hash digest
SHA256 c39f8b44c558bd6cb98383a2988a88628b3e2fb32c9a6eb9f0654ff698d5d9f7
MD5 a8486cc6eba3e317f617c6f91d9950e2
BLAKE2b-256 83b52fac31fda0597a3f1a772b3b9a1ac4baac76f9d63c8b42183a90bfbc7f6a

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page