# @coder/libghostty-vt-node ABI-stable Node-API bindings for Ghostty's `libghostty-vt` terminal state engine. This package exposes terminal VT/state semantics for Node.js consumers: feed terminal bytes, resize the terminal, read visible plain text, and extract a structured snapshot of visible rows and styled cells. It is not a screenshot, PNG, video, browser, or GUI renderer. HTML/plain formatting, where exposed, is for debugging and export only. Raster rendering remains outside this package's scope. ## Upstream References This bootstrap was written against: - Ghostty repository commit `48ccec182a932c2ec04c344d45a5fc553861cb13` - go-libghostty commit `542c76ff595ad533348e23aac74489ad095e0b36`, used only as API inspiration - Ghostty VT docs: - libghostty Doxygen: - Node-API docs: The build now pins Ghostty `v1.4.0` (`83fb95624b0439ee660c2679b43b38c8b63769cd`), which needs Zig 0.17.0. The binding talks to `libghostty-vt` directly through the C API. It has no runtime dependency on `go-libghostty`. ## API ```ts import { createTerminal, getNativeInfo } from "@coder/libghostty-vt-node"; const term = createTerminal({ cols: 80, rows: 24, scrollbackLimit: 1000 }); term.feed("hello\n"); term.feed("\x1b[31mred\x1b[0m"); // The child enables normal mouse tracking plus SGR encoding. term.feed("\x1b[?1000h\x1b[?1006h"); const mouseBytes = term.encodeMouse( { action: "press", button: "left", x: 25, y: 45 }, { geometry: { screenWidth: 800, screenHeight: 600, cellWidth: 10, cellHeight: 20, }, }, ); // Write mouseBytes to the child PTY. console.log(getNativeInfo()); console.log(term.getVisibleText()); console.log(term.snapshot({ includeCells: true })); term.dispose(); ``` The public contract is intentionally small: - `createTerminal({ cols, rows, scrollbackLimit })` - `feed(data)`, `resize(cols, rows)`, `snapshot(options)`, `getVisibleText()` - `encodeMouse(event, options)` for mode-aware terminal mouse bytes - optional debug formatters `formatPlain()` and `formatHtml()` - explicit, idempotent `dispose()` - `getNativeInfo()` for package, Node-API, platform, and Ghostty build metadata - `supportsMouseInput`, an import-time capability marker that requires no native allocation All dimensions are validated as positive integers. Using a terminal after `dispose()` throws. `snapshot()` reports the cursor position (`cursorRow`, `cursorCol`) and its DECTCEM visibility (`cursorVisible`, toggled by `ESC[?25h` and `ESC[?25l`). With `includeCells: true`, each cell reports its text, width, optional `foreground` and `background` colors, and these SGR attributes: `bold`, `faint`, `italic`, `underline`, `inverse`, `invisible`, and `strikethrough`. An attribute is present only when it is set. `inverse` is the raw SGR 7 flag: `foreground` and `background` are not swapped, so consumers apply reverse video with their own default colors. ### Mouse encoding `encodeMouse` returns a `Buffer` containing the terminal input bytes for one normalized mouse event. It returns an empty buffer when the child has mouse tracking disabled or when its negotiated mode suppresses that event. The child selects X10, UTF-8, SGR, URXVT, or SGR-pixels through the output previously passed to `feed`; callers do not choose a wire format independently. Event coordinates are finite surface-space numbers. Geometry is explicit so SGR-pixels remains accurate and the other formats can map the same position to a terminal cell. `anyButtonPressed` supplies the caller-owned aggregate button state needed for drag events outside the viewport. `trackLastCell` asks Ghostty to suppress duplicate motion events within one unchanged cell. Geometry must describe the same grid as `createTerminal` or the latest `resize`: subtract padding from the screen dimensions, then divide by cell size. The binding does not reconcile mismatched grids. Dimensions and padding must fit unsigned 32-bit integers, total padding must not exceed the screen dimensions, and the resulting grid must fit 65535 cells per axis. Coordinates are converted to 32-bit floats by the C API; after padding is removed they must fit signed 32-bit pixel coordinates and a cell index below 65536. Unrepresentable input throws `RangeError` before reaching Ghostty, including for suppressed events. Ordinary negative and off-screen positions remain supported. When UTF-8 mouse mode (1005) is set, the binding also rejects clamped cell coordinates whose encoded value would be a Unicode surrogate. This conservative guard applies while 1005 remains set even if another mouse format was selected later. Motion deduplication survives `feed()` output that leaves the negotiated tracking mode and format unchanged, as in a real terminal. It resets when the output changes the tracking mode or format, and when the geometry changes. `encodeMouse` compares the mode with the one the previous call used, so output that switches the mode and back between two calls does not reset it. SGR-pixels reports motion even within the same cell. Buttons `four`, `five`, `six`, and `seven` conventionally represent wheel up, wheel down, wheel left, and wheel right. The binding keeps Ghostty's names at this low-level API boundary so consumers can provide their own user-facing aliases. Send wheel events as `press` only: a wheel release in legacy formats is encoded as an ordinary button release. Buttons `ten` and `eleven` have no button codes in the pinned Ghostty encoder and normally produce an empty buffer; legacy release encoding still applies. ## Native Build The addon uses `node-addon-api` over Node-API/N-API and is built with `node-gyp`. Runtime loading uses `node-gyp-build`, so npm packages can ship prebuilt `.node` files. For local development: ```sh npm install npm run build:libghostty npm run build:native npm run build npm test npm run smoke ``` `npm run build:libghostty` fetches the pinned Ghostty commit into `vendor/ghostty` and installs a static `libghostty-vt` into `vendor/libghostty-vt`. The default uses `-Dsimd=false` for a dependency-minimal static library. Set `LIBGHOSTTY_VT_SIMD=true` to build SIMD support when your build environment supports it. The build targets the generic `baseline` CPU of the architecture, so the library runs on older CPUs. Set `LIBGHOSTTY_VT_CPU=native` for a local Linux build of the library tuned to your machine; do not ship it. On macOS, Ghostty's build always targets a generic macOS CPU and ignores `LIBGHOSTTY_VT_CPU`. On Linux x64, `binding.gyp` compiles the addon itself with `-march=x86-64`, because g++ on Ubuntu's amd64v3 variant (`ubuntu-latest` runners) defaults to x86-64-v3. `LIBGHOSTTY_VT_CPU` does not change the addon flags. You can also provide an existing install: ```sh LIBGHOSTTY_VT_PREFIX=/path/to/libghostty-vt npm run build:native ``` or: ```sh LIBGHOSTTY_VT_INCLUDE_DIR=/path/to/include \ LIBGHOSTTY_VT_STATIC_LIB=/path/to/libghostty-vt.a \ npm run build:native ``` If `libghostty-vt` is unavailable, `node-gyp` fails early with a setup message from `scripts/resolve-libghostty-vt.mjs`. If the built addon cannot load, the ESM loader throws a clear error with the expected recovery commands. ## Prebuilds The intended distribution path is prebuilt binaries bundled in npm packages via `npm run build:prebuild` and loaded by `node-gyp-build`. The script is named `build:prebuild` rather than `prebuild` so `npm run build` does not trigger npm's `prebuild` lifecycle hook. GitHub Actions run the same mise tasks used in development. Keep build, test, and prebuild commands in `mise.toml`; the workflow YAML should only contain GitHub-specific orchestration such as runner matrices and artifact uploads. To reset a workflow to the mise-generated baseline: ```sh mise gen github-action --write --task ci --name ci mise gen github-action --write --task release-prebuilds --name release-prebuilds ``` If a generated workflow is reset, reapply only the matrix/upload orchestration. Do not duplicate pipeline commands in `.github/workflows/*.yml`; those commands live in the `ci` and `release-prebuilds` mise tasks. Default published prebuild targets: - Linux x64 - Linux arm64 - macOS arm64 The Linux x64 prebuild targets the x86-64 baseline (x86-64-v1), so it runs on CPUs without AVX2. The compiler flags set that target. CI runs the built addon, and the release workflows run the prebuild, on an emulated `qemu64` CPU, which has no AVX, AVX2 or SSSE3. Windows is documented as unsupported for the initial package. Ghostty has C API support for Windows, but this package should only enable Windows after the build and prebuild path is verified. ## Releases Publishing is handled by `.github/workflows/publish.yml` with npm Trusted Publishing. The normal release path is a protected-main PR from a branch named `release/v*`: ```sh git checkout main git pull --ff-only origin main git checkout -b release/v0.1.0-beta.1 npm version 0.1.0-beta.1 --no-git-tag-version git add package.json package-lock.json git commit -m "Release v0.1.0-beta.1" git push origin release/v0.1.0-beta.1 ``` Open that branch as a PR into `main`. When the PR is merged, the publish workflow builds all prebuild artifacts from the merge commit, creates the matching Git tag, assembles the npm package layout, verifies the local platform prebuild, and publishes to npm. The workflow fails if the release branch does not match `package.json` exactly, such as `release/v0.1.0-beta.1`. The npm dist-tag is derived from the package version: - `0.1.0-beta.0` publishes with `--tag beta` - `0.1.0-rc.0` publishes with `--tag rc` - `0.1.0` publishes with `--tag latest` Manual dispatch and direct `v*.*.*` tag pushes are available for recovery, but merged `release/v*` PRs should be the default path. ## Dependency Updates The repository `.npmrc` sets `min-release-age=7`. When `npm install` or `npm update` picks a new version, npm skips every version published less than 7 days ago. A compromised or broken release then has a week to be found and pulled before it can reach `package-lock.json`. The setting needs npm 11.10 or later, and older npm ignores it without an error. So `devEngines` in `package.json` makes npm 10.9 and later stop with `EBADDEVENGINES` in this checkout when npm is older than 11.10. The Node version pinned in `mise.toml` ships npm 11.20. Packages that depend on this one are not affected, because npm checks `devEngines` only for the project you run it in. - `npm ci` installs exactly what the lockfile pins. It does not check release age, and neither does `npm install` for packages that the lockfile already pins. - `npm update` moves every lockfile entry younger than 7 days back to an older version, without a warning. This can undo a recent Dependabot security fix. Check the lockfile diff for downgrades and run `npm audit` before you commit. - An explicit request for a version that is too new fails with `ETARGET` ("No matching version found for ... with a date before ..."). So does `npm update` when `package.json` asks for a version that is too new. - To take a newer release on purpose, for example an urgent fix, pass `--min-release-age=0` to that one command and give the reason in the PR. - `npm audit fix` follows the same rule. If the fixed version is less than 7 days old, npm keeps the vulnerable version, warns, and exits with a non-zero code. Rerun it with `--min-release-age=0` to take the fix. - Dependabot security updates bypass this setting, so they are not delayed. The repository has no `.github/dependabot.yml`, so Dependabot opens no version-update PRs. ## Development Notes The native layer currently uses these verified `libghostty-vt` C APIs: - terminal lifecycle and stream processing: `ghostty_terminal_new`, `ghostty_terminal_set`, `ghostty_terminal_vt_write`, `ghostty_terminal_resize`, `ghostty_terminal_free` - metadata and state: `ghostty_terminal_get`, `ghostty_build_info` - mode-aware mouse input: `ghostty_mouse_encoder_*`, `ghostty_mouse_event_*` - plain/HTML debug formatting: `ghostty_formatter_terminal_new`, `ghostty_formatter_format_alloc` - structured snapshots: `ghostty_terminal_grid_ref`, `ghostty_grid_ref_cell`, `ghostty_grid_ref_graphemes`, `ghostty_grid_ref_style`, `ghostty_cell_get` The upstream API is still marked unstable by Ghostty. Keep the pinned commit updated intentionally and rerun the dogfood bundle after each pin change. ## Known Limitations - No screenshot, PNG, WebM, browser, or GUI rendering API is provided. - Structured snapshots expose visible cells and optional scrollback lines, not the full Ghostty render-state API. - Grapheme and style extraction follows the current C API and may need adjustment when Ghostty changes ABI. - On macOS, Zig native target discovery may require an explicit SDK/sysroot setup depending on the local Xcode/Zig combination. ## System Overview The package has four layers: 1. A consumer imports `dist/index.js`, which `tsc` compiles from [`src/`](https://github.com/coder/libghostty-vt-node/blob/main/src/README.md). `src/index.ts` checks arguments, and `src/loader.ts` loads the native addon with `node-gyp-build` on the first API call. 2. The addon in [`native/`](./native/README.md) wraps one libghostty-vt `GhosttyTerminal` and one `GhosttyMouseEncoder` per `TerminalWrap` object and exports `createTerminal` and `getNativeInfo`. 3. `libghostty-vt` is a static library that the addon links. `scripts/build-libghostty-vt.sh` builds it from a pinned Ghostty commit, and `binding.gyp` finds it with `scripts/resolve-libghostty-vt.mjs` (see [`scripts/`](./scripts/README.md)). 4. The release scripts in [`scripts/`](./scripts/README.md) assemble per-platform prebuilds, tag the release, and pick the npm dist-tag. [`examples/`](https://github.com/coder/libghostty-vt-node/blob/main/examples/README.md) holds the smoke script that the mise task `ci` runs last. ## Subdirectories & System Boundaries - `src`: [`src/README.md`](https://github.com/coder/libghostty-vt-node/blob/main/src/README.md) - TypeScript package API (`createTerminal`, `getNativeInfo`, `supportsMouseInput`, and the snapshot and mouse types), argument checks, disposal tracking, and the lazy, cached addon loader. - `native`: [`./native/README.md`](./native/README.md) - Node-API C++ addon (`TerminalWrap`, JavaScript class `GhosttyVtTerminal`) over the libghostty-vt C API, with per-environment class state for `worker_threads`. - `scripts`: [`./scripts/README.md`](./scripts/README.md) - libghostty-vt build and path resolver, prebuild assembly and check, release tag creation, and npm dist-tag choice. - `examples`: [`examples/README.md`](https://github.com/coder/libghostty-vt-node/blob/main/examples/README.md) - `smoke.ts`, run by `npm run smoke`. - `test` (no contract): vitest suites for the loader, the terminal API, the `encodeMouse` limits, and `worker_threads` loading. - `dogfood` (no contract): a plain-text proof bundle from the repository bootstrap. ## Global Invariants - Arguments are checked in both layers. `createTerminal` options: [src/index.ts:normalizeCreateOptions] (before the addon loads) and [native/terminal.cc:TerminalWrap::TerminalWrap]. `resize`: [src/index.ts:Terminal] and [native/terminal.cc:TerminalWrap::Resize]. `feed`: [src/index.ts:assertFeedData] and [native/terminal.cc:TerminalWrap::Feed]. `snapshot` options: [src/index.ts:normalizeSnapshotOptions] and [native/terminal.cc:TerminalWrap::Snapshot]. `encodeMouse`: [src/index.ts:normalizeMouseOptions] and [src/index.ts:normalizeMouseEvent], and [native/terminal.cc:TerminalWrap::EncodeMouse], which also guards the UTF-8 format. - The two layers throw different errors for the same input. A non-object option gets an `AssertionError` from `src/` and a `TypeError` from the addon. `src/` sets no upper bound on `cols` and `rows`, and the addon throws a `RangeError` above 65535 [native/terminal.cc:PositiveUint16]. - Both layers track disposal and throw `"GhosttyVtTerminal has been disposed"` after `dispose()`. `dispose()` is idempotent in both layers [src/index.ts:Terminal] [native/terminal.cc:TerminalWrap::DisposeNative]. - The loader requires the addon to export the functions `createTerminal` and `getNativeInfo` [src/loader.ts:assertNativeShape]. The addon sets them in [native/terminal.cc:TerminalWrap::Init] and [native/addon.cc:InitAll]. - The addon can load in the main thread and in each `worker_threads` Worker, because `TerminalWrap::Init` keeps the class constructor in per-env instance data [native/terminal.cc:TerminalWrap::Init]. - The default Ghostty commit in [scripts/build-libghostty-vt.sh:GHOSTTY_COMMIT] is the commit that "Upstream References" names. Change both together. - Build order: `npm ci`, `npm run build:libghostty`, `npm run build:native`, `npm run build`, `npm test`, `npm run smoke` [mise.toml:tasks.ci]. `npm run build:native` fails early when the libghostty-vt header or static library is missing [scripts/resolve-libghostty-vt.mjs:fail]. - `npm install` and `npm update` pick only dependency versions published at least 7 days ago [.npmrc:min-release-age]. `npm ci` installs the lockfile as pinned. npm 10.9 to 11.9 refuses to run here [package.json:devEngines]. npm 10.8 and older ignore both `min-release-age` and `devEngines`. - The npm package ships `dist`, `native`, `scripts`, `binding.gyp`, `prebuilds`, `CHANGELOG.md`, `README.md`, and `LICENSE` [package.json:files]. - A release tag is `v` from `package.json`. When `RELEASE_BRANCH_NAME` is set and not empty, it must be `release/v` [scripts/create-release-tag.mjs:releaseBranchName]. The tag must point at the checked-out `HEAD` [scripts/create-release-tag.mjs:releaseTargetSha]. - The npm dist-tag is the lower-cased first prerelease identifier, or `latest` for a plain version. A non-empty `NPM_PUBLISH_TAG` overrides it [scripts/resolve-npm-publish-tag.mjs:prerelease]. ## Global Side Effects - Network and disk: every `npm run build:libghostty` fetches the pinned Ghostty commit, by default into `vendor/ghostty`, and installs `libghostty-vt` and `ghostty-source.json`, by default into `vendor/libghostty-vt`. `GHOSTTY_SOURCE_DIR` and `LIBGHOSTTY_VT_PREFIX` change these paths [scripts/build-libghostty-vt.sh:GHOSTTY_REPO]. - Disk: `npm run build:native` runs `node-gyp rebuild` [package.json:scripts.build:native], and `npm run build` writes `dist/` [tsconfig.json:outDir]. `npm run build:prebuild` runs `prebuildify --napi` [package.json:scripts.build:prebuild]. `npm run assemble:prebuilds` replaces `prebuilds/` after its checks pass [scripts/assemble-prebuilds.mjs:targetRoot]. - Remote state: the release tag script pushes `v` to `origin` [scripts/create-release-tag.mjs:git]. The mise task `publish` runs `npm publish --access public --tag "$(node scripts/resolve-npm-publish-tag.mjs)"` [mise.toml:tasks.publish]. `.github/workflows/publish.yml` also creates or updates a GitHub Release, and `.github/workflows/release-changelog.yml` commits a `CHANGELOG.md` entry to the release PR branch, pushes it, and starts `ci.yml`. - Runtime memory: each `createTerminal` call allocates a native terminal and a mouse encoder. `dispose()` or garbage collection frees both [native/terminal.cc:TerminalWrap::~TerminalWrap]. ## System Verification - Run: `mise run ci` - `.github/workflows/ci.yml` runs the same task. Without mise, run the steps in "Native Build" above. - UBSan build of the addon: `mise run ci-ubsan`. CI runs it as the `linux-x64-ubsan` row. - Packaged-install journeys: [`.agents/skills/verify-libghostty-vt-node/SKILL.md`](https://github.com/coder/libghostty-vt-node/blob/main/.agents/skills/verify-libghostty-vt-node/SKILL.md) - TLA+ model of the native lifecycle: [`.agents/skills/verify-native-lifecycle/SKILL.md`](https://github.com/coder/libghostty-vt-node/blob/main/.agents/skills/verify-native-lifecycle/SKILL.md)