---
title: "Utilities"
description: "Terminal apps, written in TypeScript and compiled to native executables with scriptc."
canonical_url: "https://tui-sdk.dev/docs/reference/utilities"
---
# Utilities

## Keys

- `createKeyReader()` returns `{ read(input: string) }`. It turns terminal bytes into `Key` values across reads: a paste or reply can arrive in pieces, and unknown escape sequences are skipped whole.
- `matchesShortcut(key, shortcut)` compares a key with a shortcut such as `"ctrl+k"`, `"alt+enter"`, or `"shift+tab"`.

A `Key` has `name` (`KeyName`), `text`, `base`, `event` (`"press"`, `"repeat"`, or `"release"`), `ctrl`, `alt`, `shift`, `mouse?`, and `alone`. A `Mouse` has `action` (`"press"`, `"release"`, `"drag"`, `"move"`, or `"scroll-up"`, `"scroll-down"`, `"scroll-left"`, `"scroll-right"`), `button` (`"left"`, `"middle"`, `"right"`, or `"none"`), `x`, and `y`.

```ts
import { createKeyReader, matchesShortcut } from "tui"

const reader = createKeyReader()
const keys = reader.read("\x1b[A")

for (const key of keys) {
  console.log(key.name, matchesShortcut(key, "up"))
}
```

## bindTerminal

`bindTerminal(options)` takes over the terminal: the alternate screen, or the rows below the cursor when `inline`, raw keys, and bracketed paste. It restores the terminal on `restore()`, on SIGTERM, and on a crash.

| Option      | Description                                                                                             |
| ----------- | ------------------------------------------------------------------------------------------------------- |
| `onKey`     | Gets every key, paste, and reply.                                                                       |
| `onResize`  | Called with `{ columns, rows }` when the terminal changes size.                                         |
| `inline`    | Keeps the main screen and draws in the rows below the cursor.                                           |
| `onRestore` | Returns the bytes to write before the terminal is put back, such as an inline frame's end.              |
| `keyEvents` | Asks for every key's press, repeat, and release, the modifiers as keys of their own, and focus reports. |
| `mouse`     | Asks for the mouse on the alternate screen.                                                             |

It returns `columns`, `rows`, `write(bytes)`, `copy(text)`, `askBackground()`, and `restore()`.

## Motion

`createSpring(value?, options?)` returns a number that springs toward a target. `to(target)` sends it there from where it is, at the speed it has, so it never jumps; `update(frame)` moves it to the frame's time and returns where it is. While it moves, `update` calls `frame.animate()`.

Spring options are `stiffness` (170 by default), `damping` (26), `mass` (1), and `precision` (0.01). A spring also has `value`, `target`, `velocity`, `moving`, and `set(value)`.

`createTransition(value?, options?)` moves to a target over a set time on a curve. Options are `duration` (250 ms by default) and `easing` (`easeOut` by default). It has the same `value`, `target`, `moving`, `to`, `set`, and `update` as a spring.

The easings are `linear`, `easeIn`, `easeOut`, and `easeInOut`; an `Easing` is a function from progress 0 to 1 to distance 0 to 1.

```ts
import assert from "node:assert/strict"
import { createSpring, createTestApp, paint } from "tui"

const panel = createSpring(0)
panel.to(20)

const app = createTestApp({
  columns: 30,
  rows: 1,
  view: (frame) => {
    const width = Math.round(panel.update(frame))
    paint(frame, { x: 0, y: 0, columns: width, rows: 1 }, frame.theme.primary)
  },
})

for (let step = 0; step < 60; step++) {
  app.advance(16)
}
assert.ok(panel.value > 19)
console.log(panel.value)
```

## Prompts

`tui/prompt` asks questions and shows work in progress in the rows below the cursor, and leaves the answers in the terminal's scrollback. Each prompt resolves with its answer, or `null` when someone cancels it with Ctrl+C or Escape.

- `text(options)` asks for a line: `message`, `placeholder?`, `defaultValue?`, `validate?(value)`, `theme?`. Resolves to `string | null`.
- `select(options)` asks for one of `items`: `message`, `items`, `defaultValue?` (the item highlighted first), `visible?` (7 by default), `theme?`. Resolves to `string | null`.
- `multiselect(options)` checks items with Space: `message`, `items`, `defaultValues?`, `visible?`, `required?`, `theme?`. Resolves to `readonly string[] | null`.
- `confirm(options)` asks a yes or no question: `message`, `defaultValue?` (true by default), `theme?`. Resolves to `boolean | null`.
- `spinner(options)` returns `{ update(message), stop(message?), fail(message?) }`.
- `progress(options)` takes `message` and `max`, and returns `{ update(value, message?), stop(message?), fail(message?) }`.

When the output is not a terminal, a spinner or progress line writes only the line it ends with.

```ts
import { confirm, select, spinner, text } from "tui/prompt"

const name = await text({ message: "Project name", placeholder: "my-app" })
const template = await select({
  message: "Template",
  items: [
    { value: "app", label: "App" },
    { value: "api", label: "API" },
  ],
})
const install = await confirm({ message: "Install dependencies?" })
if (name === null || template === null || install === null) {
  process.exit(130)
}
if (install) {
  const installing = spinner({ message: "Installing" })
  await new Promise((resolve) => setTimeout(resolve, 100))
  installing.stop("Installed")
}
console.log(name, template, install)
```

The prompts are apps like any other. `runApp({ view, rows: 3 })` draws your own app in three rows below the cursor instead of on the whole screen.

## Agents

`tui/agent` lets people give an AI agent the app while it runs in their terminal.

`agentServer({ name, allow })` is given to `runApp` as `agent`. `yourapp mcp` is then an MCP server for the running app. Its two tools are `snapshot`, which lists every drawn component with its state, items, and actions, and the screen as text; and `act`, which runs steps through those actions or through keys. `allow(action)` decides each step before it runs.

```ts
import { type Frame, Listbox, runApp } from "tui"
import { agentServer } from "tui/agent"

const files = ["README.md", "package.json", "src", "test"].map((value) => ({ value, label: value }))

function view(frame: Frame) {
  Listbox.Root(frame, { id: "files", label: "Files", items: files }, (root) =>
    Listbox.Content(root, frame.rect),
  )
}

runApp({
  view,
  agent: agentServer({
    name: "files",
    allow: (step) => step.component !== "dialog",
  }),
})
```

Every change an agent makes reports the source `"agent"` to the component's change callback. A component drawn with `agent: "secret"` reads its values as `"[redacted]"`, and one with `agent: "hidden"` is not listed.

`createAgent(app, { allow? })` gives the same `snapshot()` and `act({ steps })` to code of your own. It takes what `runApp` or `createTestApp` returns. `agentTools` describes the two as tools for a model, with names, descriptions, and input schemas.
