Skip to content
20 changes: 20 additions & 0 deletions .changeset/color-encoding-tiers.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
---
'@bomb.sh/tty': minor
---

Adds capability-aware SGR color encoding to the renderer.

The renderer now derives its color encoding from terminal capability evidence instead of always emitting 24-bit truecolor. Terminals with truecolor evidence (`RGB`/`Tc`, `COLORTERM`, direct-color `max_colors`, or a `colordepth` probe folded through `term.update()`) continue to receive byte-identical truecolor output. Without truecolor evidence, cells emit 256-color SGR (`\x1b[38;5;Nm`) when `colors > 16`, or 4-bit SGR (`\x1b[31m`) at or below 16. Colors are downmapped deterministically. In 256-color output, RGB colors map onto the 6×6×6 cube and grayscale ramp (`rgba(255, 0, 0)` → `\x1b[38;5;196m`), never onto indices 0–15, which follow the terminal's theme. In 16-color output, they map to the nearest standard palette entry. Use the `-ansi-*` keywords when you want the terminal's own palette colors. A tier change between frames forces a complete redraw.

The baseline — no capability evidence — now resolves to 256-color rather than truecolor. Pass `detectTerminal()` output to `createTerm` to restore truecolor output on terminals that support it.

#### Migration

```diff
import { createTerm } from "@bomb.sh/tty";
+ import { detectTerminal } from "@bomb.sh/tty";

- const term = await createTerm({ width, height });
+ const terminfo = await detectTerminal();
+ const term = await createTerm({ width, height, terminfo });
```
193 changes: 193 additions & 0 deletions specs/color-encoding-spec.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,193 @@
# Clayterm Color Encoding Specification

**Version:** 0.1 (draft) **Status:** Proposed. Normative for the SGR color
encoding of rendered cells.

---

## 1. Purpose

The renderer encodes every non-default cell color as an SGR sequence. This
specification defines which encoding the renderer emits for a given capability
snapshot, and how 24-bit colors map into the 256-color and 16-color palettes
when the terminal lacks truecolor support.

The capability snapshot ([terminfo-spec.md](terminfo-spec.md)) is the only input
that selects the encoding. There is no caller-facing override: callers control
the encoding by supplying capability evidence, either a terminfo entry at
creation or probe responses folded through `update()`.

---

## 2. Scope

### In scope

- How `trueColor` and `colors` in the capability snapshot select the encoding
tier
- The SGR format for foreground and background colors in each tier
- The mapping from 24-bit RGB to the 256-color and 16-color palettes
- Output when the tier changes between renders

### Out of scope

- **The terminal's palette.** The renderer emits palette _indices_. How a
terminal renders index N is the terminal's concern.
- **An 8-color tier.** Terminals reporting fewer than 16 colors use the 16-color
tier (§5).
- **88-color precision.** Terminals reporting `17 ≤ colors ≤ 255` use the
256-color tier (§5).

---

## 3. Terminology

**Color tier.** One of `"truecolor" | "256" | "16"`, the `ColorDepth` type
defined in [terminfo-spec.md](terminfo-spec.md) §6.2. The tier names the
emission encoding, not the terminal's full capability set.

**Downmapping.** Producing the SGR sequence that represents a 24-bit RGB color
under a narrower tier.

**Nominal palette.** The 16-entry RGB table defined in §7.1. It is the
renderer's model of what each 4-bit index means when the `"16"` tier picks the
nearest index. It is not a claim about any terminal's actual palette.

**Fixed color.** An sRGB value. Its intended appearance does not depend on the
terminal's theme, unlike a terminal-themed color (renderer-spec §8.5).

---

## 4. Invariants

- **CI-1 — Total, deterministic resolution.** Every capability snapshot resolves
to exactly one tier by the rule in §5. The tier depends only on the capability
snapshot; resizing the Term does not change it.
- **CI-2 — Truecolor is exact.** Under the `"truecolor"` tier, every RGB color
is emitted with its exact channel values.
- **CI-3 — Deterministic downmapping.** Every downmapping decision in §7 is a
pure function of the RGB value and the tier. Ties resolve to the lowest index.
- **CI-4 — Fixed colors stay off the themed palette where possible.** Under the
`"256"` tier, an sRGB color never maps to indices 0–15, which the terminal's
theme controls. Every color of the cube or grayscale ramp (indices 16–255)
maps to its own index. Under the `"16"` tier no fixed alternative exists, so
an sRGB color maps to the nearest nominal palette entry, and every nominal
palette entry maps to its own index.
- **CI-5 — Tier change redraws.** When the tier differs from the previous
render's tier, the next render emits every cell, encoded in the new tier.
- **CI-6 — Terminal-themed colors are tier-independent.** Terminal default and
palette colors emit as renderer-spec §8.5 specifies, identically in every
tier. Style attributes (bold, dim, italic, underline, blink, reverse,
strikeout) also emit identically in every tier.

---

## 5. Tier resolution

The renderer resolves the tier from the capability snapshot:

```
tier =
trueColor ? "truecolor"
: colors <= 16 ? "16"
: "256"
```

The `colors ≤ 16` boundary matches the denial mapping in terminfo-spec §6.3, so
the tier agrees with a `colordepth` denial event for every static `colors`
value. A `colordepth` probe event folds into `trueColor`; no other fold changes
the tier.

- `colors` values below 16, including a missing `max_colors` (0), resolve to the
`"16"` tier.
- Truecolor requires positive evidence (terminfo-spec §7.1): the `RGB`/`Tc`
terminfo extension, `COLORTERM`, a direct-color entry (`max_colors ≥ 2²⁴`), or
a `colordepth` probe response.
- With no evidence (the terminfo-spec §7.1 baseline), the tier is `"256"`.

---

## 6. Emission formats

For a non-default foreground or background under each tier:

| Tier | Foreground | Background |
| ------------- | --------------------------------------------- | ---------------------------------------------- |
| `"truecolor"` | `\x1b[38;2;R;G;Bm` | `\x1b[48;2;R;G;Bm` |
| `"256"` | `\x1b[38;5;Nm`, N ∈ 0–255 | `\x1b[48;5;Nm`, N ∈ 0–255 |
| `"16"` | index 0–7: `\x1b[3Nm`; index 8–15: `\x1b[9Nm` | index 0–7: `\x1b[4Nm`; index 8–15: `\x1b[10Nm` |

In the `"16"` tier, `N` is the palette index for indices 0–7 and `index − 8` for
indices 8–15. Standard red (index 1) emits `\x1b[31m` foreground and `\x1b[41m`
background.

---

## 7. Downmapping

### 7.1 Nominal palette

| Index | RGB | Name | Index | RGB | Name |
| ----- | --------- | ------- | ----- | --------- | -------------- |
| 0 | `#000000` | black | 8 | `#808080` | bright black |
| 1 | `#ff0000` | red | 9 | `#ff5555` | bright red |
| 2 | `#00ff00` | green | 10 | `#55ff55` | bright green |
| 3 | `#ffff00` | yellow | 11 | `#ffff55` | bright yellow |
| 4 | `#0000ff` | blue | 12 | `#5555ff` | bright blue |
| 5 | `#ff00ff` | magenta | 13 | `#ff55ff` | bright magenta |
| 6 | `#00ffff` | cyan | 14 | `#55ffff` | bright cyan |
| 7 | `#c0c0c0` | white | 15 | `#ffffff` | bright white |

The primaries (1–6) are the pure hues and the bright variants are their pastel
counterparts. The `"16"` tier uses this table to choose the nearest index
(§7.2); the `"256"` tier does not use it.

In the `"16"` tier, the named color `red` and `-ansi-red` both emit palette 1,
because the tier has no other way to show red. The terminal's theme decides what
palette 1 looks like. In the `"256"` and `"truecolor"` tiers, `red` is a fixed
color, while `-ansi-red` is palette 1 in every tier (§7.4).

### 7.2 `"16"` tier

Map the RGB value to the nearest nominal palette entry by squared Euclidean
distance over the three channels. On a tie, choose the lowest index.

### 7.3 `"256"` tier

The tier maps sRGB colors only onto the 6×6×6 cube (indices 16–231) and the
grayscale ramp (indices 232–255). It never emits indices 0–15, because the
terminal's theme controls them. Standard red emits `\x1b[38;5;196m`.

The first matching rule wins:

1. **Exact cube match.** If every channel is one of the six cube values
`{0, 95, 135, 175, 215, 255}`, emit `16 + 36r + 6g + b` for the channels'
cube steps. Gray cube values such as `#5f5f5f` resolve here.
2. **Grayscale.** If `r == g == b`, choose the nearest value among the grayscale
ramp `{8 + 10i : 0 ≤ i ≤ 23}` extended by the endpoints `0` (index 16) and
`255` (index 231). On a tie, choose the lower index. Emit `232 + i` for ramp
value `8 + 10i`, `16` for the low endpoint, and `231` for the high endpoint.
3. **Cube nearest.** Otherwise, map each channel to the nearest cube value (ties
to the smaller value) and emit `16 + 36r + 6g + b`.

### 7.4 Resolved colors

The tier applies to a cell's resolved color, after the render-time field
resolution of renderer-spec §8.5 (foreground inheritance, `currentcolor`, and
system colors). A resolved color is one of:

- **sRGB.** Encoded for the active tier by §6 and §7. This includes a
cross-field `Canvas` or `CanvasText` resolved to a probed theme color, and a
`currentcolor` or inherited color that resolves to sRGB.
- **Terminal default or palette entry.** Not downmapped. It emits as
renderer-spec §8.5 specifies, in every tier (CI-6).

Downmapping reads only a color's RGB channels and never alters style attribute
emission.

---

## 8. Tier changes

An `update()` that changes the tier returns no bytes (renderer-spec §7.7). The
next render emits a complete redraw in the new tier (CI-5).
35 changes: 18 additions & 17 deletions specs/renderer-spec.md
Original file line number Diff line number Diff line change
Expand Up @@ -471,12 +471,9 @@ is valid until the next `render()` **or** `update()` call).
The renderer consumes the read-only capability snapshot maintained by
`Term.update()`. A protocol that changes emitted bytes MUST define its gating
capability, output, and invalidation rules in its own section of this
specification. Synchronized output (§7.9) and pointer shape (§7.10) are
specified so far.

Color encoding, Kitty keyboard mode setup, and Kitty graphics emission are
deferred to their respective follow-up PRs. The renderer continues to emit its
existing hardcoded ANSI output until each is specified.
specification or a companion specification: synchronized output (§7.9), pointer
shape (§7.10), and color encoding
([Color Encoding Specification](color-encoding-spec.md)).

### 7.9 Synchronized output (DEC mode 2026)

Expand Down Expand Up @@ -601,7 +598,9 @@ parameters specify the terminal dimensions in character cells.
The optional `terminfo` value (from `detectTerminal()`; see
[Terminfo Specification](terminfo-spec.md) §10.1) initializes the Term's private
`RuntimeCapabilities` from the static `Capabilities` it carries. When omitted,
the Term uses the §7.1 baseline.
the Term uses the §7.1 baseline. The renderer resolves its color encoding from
this capability snapshot; the derivation rule and downmapping behavior are
specified in the [Color Encoding Specification](color-encoding-spec.md).

### 8.2 Render invocation

Expand Down Expand Up @@ -855,16 +854,17 @@ The renderer reads this from the OSC 10/11 theme probe, surfaced as
`RuntimeCapabilities.theme.foreground` / `.background` (terminfo-spec §6.4),
using the theme in effect when the frame renders. The result is an ordinary
opaque sRGB color (alpha 255): it renders exactly like the equivalent `rgba()`
value, as truecolor. When the theme has not yet reported that color, the keyword
falls back to its field's own terminal default instead (the same-field behavior
above). A theme report that `update()` folds in after a frame renders takes
effect starting with the next render.
value, encoded for the active color tier
([Color Encoding Specification](color-encoding-spec.md) §5). When the theme has
not yet reported that color, the keyword falls back to its field's own terminal
default instead (the same-field behavior above). A theme report that `update()`
folds in after a frame renders takes effect starting with the next render.

For example, once the terminal has reported its default foreground color,
`text({ bg: "CanvasText" })` paints that color as an opaque truecolor
background. Until then it falls back to the default background: a terminal
offers no way to paint its default foreground color as a cell background without
knowing its RGB value, and the renderer never guesses one.
`text({ bg: "CanvasText" })` paints that color as an opaque background. Until
then it falls back to the default background: a terminal offers no way to paint
its default foreground color as a cell background without knowing its RGB value,
and the renderer never guesses one.

A terminal-themed color (a same-field default, or a palette entry) is opaque. A
palette color in a foreground field is emitted as SGR `30`–`37` for palette 0–7
Expand All @@ -881,8 +881,9 @@ including cells an enclosing element painted. This is distinct from an omitted
Cell diffing treats terminal-themed colors like any other attribute: a cell
whose color changes between a palette color, a terminal default, and an sRGB
color in consecutive frames MUST be re-emitted, and an unchanged cell MUST NOT
be. The renderer does not resolve a palette color to RGB to compare it with an
sRGB color.
be, except after a color tier change
([Color Encoding Specification](color-encoding-spec.md) CI-5). The renderer does
not resolve a palette color to RGB to compare it with an sRGB color.

Transitions have special considerations for terminal-themed colors; see
Transitions Specification §7.4.
Expand Down
Loading
Loading