API: TerminalBackend
import type { TerminalBackend, TerminalOptions, TerminalCapabilities } from "@termless/core"TerminalBackend Interface
All backends must implement this interface. Users typically don't interact with backends directly -- createTerminal() wraps them.
interface TerminalBackend extends Terminal {
readonly name: string
// Lifecycle
init(opts: TerminalOptions): void
destroy(): void
// Data flow
feed(data: Uint8Array): void
resize(cols: number, rows: number): void
reset(): void
// Key encoding
encodeKey(key: KeyDescriptor): Uint8Array
// Scrollback
// Compatibility no-op when capabilities.productViewport declares absence;
// probes omit this control for that library subject.
scrollViewport(delta: number): void
// Capabilities
readonly capabilities: TerminalCapabilities
}capabilities.productViewport?: { available: false; reason: string } records audited absence of a viewport in the library subject. Undefined means undeclared. WezTerm Screen and libvterm retain the required scrollViewport compatibility no-op; probes never read it when this declaration is present. The reason cites the pinned library interface, not the enclosing application's viewport.
Clipboard callback state
The optional getClipboardState() reader returns a copied snapshot of writes accepted by the engine's clipboard callback. It does not prove that the OS clipboard changed, and the input-scanned Terminal.clipboardWrites is not a substitute for this reader.
Alacritty records its ClipboardStore requests per backend instance, in order. Its selector is the engine's selection class: c for clipboard, p for primary selection, including the engine's s alias. Its text is the decoded UTF-8 text accepted by the engine; payload is a canonical base64 re-encode of that text, not the original wire bytes. In contrast, the vt100-rust callback retains the wire payload. Malformed base64 or non-UTF-8 writes produce no Alacritty entry, not a decodeError entry.
Reading does not drain the history, and RIS does not clear it. Reinitializing the backend creates a new instance with empty history; changing the returned snapshot cannot change that history. Alacritty enables Osc52::CopyPaste and reports control: ["osc52=CopyPaste"]. Its ClipboardLoad handler uses the engine's formatter to answer from the last preceding write for that selection, or empty text when no write exists. The engine preserves the query selector and terminator. Alacritty does not supply pasteSelector. A poisoned callback-state lock is reported as an error by the reader, never as an empty successful snapshot.
WezTerm records decoded Clipboard::set_contents callbacks, with c for its clipboard and p for primary selection. An engine clear callback records empty text. Its snapshots have the same instance lifetime and copying behavior; the engine's clipboard-read requests remain silent. Neither reader accesses the operating system clipboard.
Stored cell observations
WezTerm declares semantic-cells and cell-images. The corresponding optional extensions expose getCellSemanticType(row, col) and getCellImageCount(row, col). Both use the same absolute buffer coordinates as getCell and throw for invalid coordinates. The image count reads actual attachments held by the engine's cell; zero means no attached images. It does not measure rendered pixels. The semantic type reads current prompt, input or output state, not mark history or command completion.
TerminalOptions
interface TerminalOptions {
cols: number
rows: number
scrollbackLimit?: number
}TerminalCapabilities
Describes what features a backend supports. Terminal capability data across real terminals is maintained at terminfo.dev.
interface TerminalCapabilities {
name: string // e.g. "xterm"
version: string // upstream engine release pinned by this backend
truecolor: boolean // 24-bit RGB colors
kittyKeyboard: boolean // Kitty keyboard protocol
kittyGraphics: boolean // Kitty graphics protocol
sixel: boolean // Sixel image support
osc8Hyperlinks: boolean // OSC 8 clickable links
semanticPrompts: boolean
unicode: string // e.g. "15.1"
reflow: boolean // Text reflow on resize
extensions: Set<string> // Optional extension identifiers
}capabilities.version is the upstream engine release pinned by upstreamVersion in backends.json for the default install ("not-applicable" without an upstream), not the wrapper release or proof of execution; non-default installs are outside this claim and a run's runtimeIdentity supplies execution evidence. A request for a non-default backend(name, { version }) is refused.
Available Backends
xterm.js
import { createXtermBackend } from "@termless/xtermjs"
const backend = createXtermBackend()
// or with eager initialization:
const backend = createXtermBackend({ cols: 80, rows: 24 })Uses @xterm/headless for in-process terminal emulation. No browser needed.
Ghostty
import { createGhosttyBackend, initGhostty } from "@termless/ghostty"
// WASM must be loaded first
const ghostty = await initGhostty()
const backend = createGhosttyBackend(undefined, ghostty)
backend.init({ cols: 80, rows: 24 })Implementing a Custom Backend
To create a new backend, implement the full TerminalBackend interface:
import type { TerminalBackend, TerminalOptions, Cell /* ... */ } from "@termless/core"
export function createMyBackend(): TerminalBackend {
return {
name: "my-backend",
init(opts: TerminalOptions) {
/* initialize with cols/rows */
},
destroy() {
/* cleanup */
},
feed(data: Uint8Array) {
/* process terminal data */
},
resize(cols, rows) {
/* resize terminal */
},
reset() {
/* reset to initial state */
},
getText() {
/* return all text */
},
getTextRange(sr, sc, er, ec) {
/* return text range */
},
getCell(row, col) {
/* return Cell */
},
getRow(row) {
/* return Cell[] */
},
getRows() {
/* return Cell[][] */
},
getCursor() {
/* return Cursor */
},
getMode(mode) {
/* return boolean */
},
getTitle() {
/* return string */
},
getIconLabel() {
/* optional: return string when backend tracks engine icon-name state */
},
getScrollback() {
/* return ScrollbackState */
},
encodeKey(key) {
/* encode KeyDescriptor to bytes */
},
scrollViewport(delta) {
/* scroll by delta lines */
},
capabilities: {
name: "my-backend",
version: "not-applicable",
truecolor: true,
kittyKeyboard: false,
kittyGraphics: false,
sixel: false,
osc8Hyperlinks: false,
semanticPrompts: false,
unicode: "15.1",
reflow: false,
extensions: new Set(),
},
}
}Extension Interfaces
osc8Hyperlinks declares clickable-link feature support; the hyperlinks extension separately exposes per-cell URI metadata through getHyperlinkAt.
Backends can optionally implement extension interfaces. Use hasExtension() to check:
import { hasExtension } from "@termless/core"
// Native mouse encoding (extension name "mouse-encoding")
interface MouseEncodingExtension {
encodeMouse(event: MouseEvent): Uint8Array | null
}
// Native paste encoding (extension name "paste-encoding")
interface PasteEncodingExtension {
encodePaste(text: string): Uint8Array
}
// Color palette manipulation
interface ColorPaletteExtension {
setColorPalette(entries: Partial<Record<number, Color>>): void
setDefaultFg(color: Color): void
setDefaultBg(color: Color): void
}
// Dirty row tracking (for incremental rendering)
interface DirtyTrackingExtension {
getDirtyRows(): Set<number>
clearDirty(): void
}
// Hyperlink detection
interface HyperlinkExtension {
getHyperlinkAt(row: number, col: number): string | null
}
// OSC parser metadata (extension name "osc-metadata")
interface OscMetadataExtension {
getUnhandledSequences?(): readonly { readonly kind: "osc" | "csi"; readonly code: string }[]
getCwd(): string | null
getNotifications(): readonly string[]
}
// Track A compatibility read; migrate onto Emulator with TerminalBackend at A4b.
// "semantic-marks" declares starts; "semantic-command-end" declares ends.
interface SemanticStartMark {
readonly type: "prompt" | "command" | "output"
readonly startRow: number
readonly startCol: number
}
type SemanticMark =
| SemanticStartMark
| {
readonly type: "command-end"
readonly rawStatus: string
}
interface SemanticMarkExtension {
getSemanticMarks(): readonly SemanticMark[]
}
// Track A compatibility read; migrate onto Emulator or delete with TerminalBackend at A4b.
// Extension name "sixel-storage"; storage is not raster rendering.
interface SixelStorageExtension {
getSixelImages(): readonly {
readonly data: string
readonly row: number
readonly col: number
}[]
}
// Bell counter
interface BellExtension {
getBellCount(): number
clearBellCount(): void
}PasteEncodingExtension is declared by "paste-encoding". encodePaste(text) returns the engine's native input bytes in its current mode, including its own framing and text rules. It preserves modes and queued replies, does not feed the parser or write to a PTY, and never calls the backend's onResponse. Libvterm, WezTerm, vt100, vt220, vterm, Kitty and Ghostty-native implement it. Kitty uses native Screen paste policy rather than application-level Window sanitization. Ghostty-native normalizes controls to spaces; outside bracketed mode it also converts line feeds to carriage returns. The historical vt100/vt220 encoders never frame paste; modern vterm follows its native mode 2004 and removes payload framing markers only while bracketed. Those three native libraries preserve newlines regardless of LNM. Another backend may omit the extension when no path is exposed.
OscMetadataExtension exposes the engine's exact OSC 7 URI and copied, ordered OSC 9 payloads. Null cwd means the engine reports no URI. Notification payloads retain their raw strings; this reader does not attest an OS notification appearing or OSC 9;4 progress behavior. Check hasExtension<OscMetadataExtension>(backend, "osc-metadata") before calling these methods. The vterm backend implements them; other backends can omit the extension.
Libvterm, vt100-rust, VT100.js and VT220.js expose getUnhandledSequences(): copied, ordered reports from the library's own unhandled callbacks. OSC code is only its command number; vt100-rust CSI code retains native normalized parameter groups (colon and semicolon separated), with intermediate characters in front and the final byte last, such as 5m, 4:3m or ?5m. These are callback values, not raw input spelling. History clears with the same callback owner as OSC 9 and 777 on reset/re-init. A missing member is missing evidence; an empty report decides nothing. A report can witness a state feature the library did not handle, while a delivery feature can succeed through that same callback. Recording the callback does not create library state or change how the library handles the sequence.
Kitty exposes the same getter from its native diagnostic-parser error rows, separately from host delivery. Its message parser is pinned to 0.49.2; unmatched messages and other versions contribute no entry. CSI codes keep only the reported modifiers and final byte, never omitted parameters. Batch replay retains the ordered feed history until re-init.
VT100.js reports completed OSC command numbers only, without payloads, and finite non-negative safe-integer operands its SGR path ignored, with m appended. It does not reconstruct discarded colon groups. Its engine keeps at least the most recent 1000 entries, trimming oldest entries after 2000; reset/re-init clear them. Before initialization or after destroy the adapter retains its normal lifecycle error. The extension adds no Cwd, notification, or other metadata reader on VT100.js.
VT220.js also forwards its native engine's completed OSC command numbers and ignored numeric SGR operands. Reports contain copied, ordered summaries without payloads; an empty report decides nothing. Init/re-init starts fresh, reset/RIS clears observations, and calls before initialization or after destroy use the normal lifecycle error. Other optional metadata readers remain absent.
The vterm and xterm.js backends also expose getOsc777Payloads(): copied, ordered payloads from their public completed-OSC callbacks, including non-notify payloads. History follows that parser instance across reset and starts empty on re-init; this observes parser events and does not attest OS notification delivery.
Check hasExtension<SemanticMarkExtension>(backend, "semantic-marks") for start observations or hasExtension<SemanticMarkExtension>(backend, "semantic-command-end") for end observations. Both keys use the same getter; an engine recording both kinds declares both keys. Narrow mark.type before reading variant fields. vterm declares only starts; Kitty and Ghostty native declare starts and ends. Each read returns copied, ordered records; an empty array means no stored records, while an absent key means that kind of observation is not declared. vterm reset and snapshot restore clear its starts. Kitty's cumulative callback history survives reset and batch replay, preserves duplicate entries and is cleared by a new init() or destroy().
Start positions are zero-based screen coordinates captured at insertion, not absolute buffer rows or tracked zone boundaries. Command-end entries have no coordinates. Kitty preserves the native raw status string verbatim, including an empty string, "0", negative-looking and nonnumeric strings; it is not a validated process exit status. Neither variant supplies command text or bounded zones.
Ghostty native retains its library's typed semantic action in the adapter: the library itself keeps no command-end status. Its raw status is the original first token only when the pinned engine's exit-code reader accepts it; D;0017 keeps "0017", while D;aid=9 and bare D yield "". Start coordinates follow the engine effect, including A's fresh-line movement. Its semantic-cells reader returns the actual stored cell type at the same row origin as getCell and throws for invalid coordinates. Reset/RIS resets engine cell semantics; retained action history survives until re-init/destroy. Every read returns independent copies.
MouseShapeExtension (mouse-shape) exposes getMouseShape(): string: logical W3C pointer state, separate from the text caret. Ghostty native starts at text, resolves aliases in the engine, ignores unknown names and preserves the actual pointer through reset/RIS; re-init starts fresh. The getter requires a live handle. Its existing kittyGraphics capability reads the flag compiled into the addon.
Ghostty native's optional getClipboardState() retains typed clipboard actions, not OS clipboard delivery. Writes keep the engine's raw encoded payload and selector without inventing decoded text. Only an exact ? request sets pasteSelector; the adapter supplies no clipboard reply. Copied, non-draining history survives reset/RIS and starts fresh on re-init/destroy.
Check hasExtension<SixelStorageExtension>(backend, "sixel-storage") before reading vterm's copied raw image records; reset and snapshot restore clear those records. Sixel data is the exact stored payload after q, without DCS framing or parameters. Its row/column locate the DCS start, not the image extent. Neither this reader nor the protocol capability flag establishes raster rendering or cell geometry.