# Terset docs

> Install Terset for JavaScript or Python, encode your first table, and look up every function, error and limit.

## Install

Version 0.4.0 for JavaScript and Python. The encoder writes format version 1.2 by default. Text written in format 1.0 still decodes. Format 1.1 text also decodes. Write 1.1 with `encode(value, { format: "1.1" })` in JavaScript or `encode(value, format="1.1")` in Python. Use `"1.0"` for 1.0 text.

| Language | Package | Install | Conformance |
| --- | --- | --- | --- |
| JavaScript | [@stackdeck/terset](https://www.npmjs.com/package/@stackdeck/terset) | `pnpm add @stackdeck/terset` | Passes the 1.0, 1.1, and 1.2 suites |
| Python | [terset](https://pypi.org/project/terset/) | `pip install terset` | Passes the 1.0, 1.1, and 1.2 suites |

Both packages run the shared test suites at [conformance/](https://github.com/stackdeckhq/terset/tree/main/conformance) for 1.0, [conformance/1.1/](https://github.com/stackdeckhq/terset/tree/main/conformance/1.1) for 1.1, and [conformance/1.2/](https://github.com/stackdeckhq/terset/tree/main/conformance/1.2) for 1.2.

### JavaScript

```sh
pnpm add @stackdeck/terset
```

```sh
npm install @stackdeck/terset
```

```sh
yarn add @stackdeck/terset
```

```sh
bun add @stackdeck/terset
```

Zero dependencies. Node 20 and up. Types are included.

### Python

```sh
pip install terset
```

Zero dependencies. Python 3.10 and up. Type hints are included.

## Quick start

Encode the data, send the fitted rules with it, and decode to check the round trip.

### JavaScript

Save this as `example.mjs`.

```js
import { rulesFor, decode, encode } from "@stackdeck/terset";

/** @type {import("@stackdeck/terset").JsonRoot} */
const data = {
  team: "core",
  users: [
    { id: "u1", name: "Ada", role: "admin" },
    { id: "u2", name: "Ben", role: "ops" },
    { id: "u3", name: "Chen" },
  ],
};

const text = encode(data);

// One text: send its fitted rules right before the data.
const messages = [
  { role: "system", content: "You read Terset data." },
  { role: "user", content: `Which users have no role?\n\n${rulesFor(text)}\n${text}` },
];

console.log(text);
console.log(JSON.stringify(decode(text)) === JSON.stringify(data)); // true
```

```sh
node example.mjs
```

Output (the gaps are tabs):

```text
team: core
users[3]:
id	name	name=value
u1	Ada	role=admin
u2	Ben	role=ops
u3	Chen
true
```

1. `encode(value)` turns a JSON object or array into Terset text.
2. Send `rulesFor(text)` right before the data. A shared or cached system prompt for many texts takes `RULES` instead.
3. `decode(text)` gives back the same value. Ask the model to answer in JSON, since Terset is for reading.

#### JavaScript details

- Terset ships as an ES module. In a CommonJS project, use `await import("@stackdeck/terset")` inside an async function.
- `decode` and `rulesFor` throw `SyntaxError` on any text they reject, and `TypeError` when the input is not a string.
- Values must be plain objects, arrays and JSON scalars. Class instances, symbol keys and sparse arrays throw `TypeError`.
- Numbers are JavaScript numbers. Numeric `-0`, `NaN` and infinities throw `TypeError`.

### Python

Save this as `example.py`.

```python
from terset import JsonRoot, decode, encode, rules_for

data: JsonRoot = {
    "team": "core",
    "users": [
        {"id": "u1", "name": "Ada", "role": "admin"},
        {"id": "u2", "name": "Ben", "role": "ops"},
        {"id": "u3", "name": "Chen"},
    ],
}

text = encode(data)

# One text: send its fitted rules right before the data.
messages = [
    {"role": "system", "content": "You read Terset data."},
    {"role": "user", "content": f"Which users have no role?\n\n{rules_for(text)}\n{text}"},
]

print(text)
print(decode(text) == data)  # True
```

```sh
python3 example.py
```

Output (the gaps are tabs):

```text
team: core
users[3]:
id	name	name=value
u1	Ada	role=admin
u2	Ben	role=ops
u3	Chen
True
```

1. `encode(value)` turns a JSON object or array into Terset text.
2. Send `rules_for(text)` right before the data. A shared or cached system prompt for many texts takes `RULES` instead.
3. `decode(text)` gives back the same value. Ask the model to answer in JSON, since Terset is for reading.

#### Python details

- `decode` and `rules_for` raise `ValueError` on any text they reject, and `TypeError` when the input is not a string.
- Numbers follow JavaScript, so `1.0` writes as `1`. Decoded whole numbers within `[-2**53, 2**53]` become `int`. Others become `float`.
- An `int` that a binary64 float cannot hold exactly, such as `9007199254740993`, raises `TypeError` instead of rounding.
- Numeric `-0`, `nan`, infinities, cycles and types other than `dict`, `list`, `str`, numbers, `bool` and `None` raise `TypeError`.
- Dictionary order is kept, with array-index keys such as `"2"` and `"10"` first, in numeric order, as in JavaScript.
- `encode` takes the read-only `JsonInputRoot` type. `decode` returns `JsonRoot`. The package ships `py.typed`.

Never write Terset by hand. Always use `encode`.

## Cheat sheet

Common shapes, as JSON and as the text `encode` writes for them. The Terset side is made by the encoder when the site builds. The gaps are tabs.

### Uniform rows

A root list of records becomes `[N]`, one header and one row per record.

```json
[
  {
    "id": "a1",
    "name": "Ada",
    "age": 36
  },
  {
    "id": "b2",
    "name": "Ben",
    "age": 41
  },
  {
    "id": "c3",
    "name": "Chen",
    "age": 29
  }
]
```

```terset
[3]
id	name	age
a1	Ada	36
b2	Ben	41
c3	Chen	29
```

### Uneven rows

Fields every row has are columns. The other fields follow as `name=value` cells, only in the rows that have them.

```json
{
  "users": [
    {
      "id": "u1",
      "name": "Ada",
      "role": "admin"
    },
    {
      "id": "u2",
      "name": "Ben"
    },
    {
      "id": "u3",
      "name": "Chen",
      "role": "ops",
      "team": "core"
    }
  ]
}
```

```terset
users[3]:
id	name	name=value
u1	Ada	role=admin
u2	Ben
u3	Chen	role=ops	team=core
```

### Nested objects

When every row has the same nested keys, they become dotted columns.

```json
{
  "orders": [
    {
      "id": "o1",
      "ship": {
        "city": "Lisbon",
        "zip": "1100"
      }
    },
    {
      "id": "o2",
      "ship": {
        "city": "Porto",
        "zip": "4000"
      }
    },
    {
      "id": "o3",
      "ship": {
        "city": "Braga",
        "zip": "4700"
      }
    }
  ]
}
```

```terset
orders[3]:
id	ship.city	ship.zip
o1	Lisbon	"1100"
o2	Porto	"4000"
o3	Braga	"4700"
```

### Keyed map

A map of records can become `name{N}`. The `@key` column holds each key.

```json
{
  "servers": {
    "web": {
      "cpu": 2,
      "ram": 4,
      "zone": "eu"
    },
    "db": {
      "cpu": 8,
      "ram": 32,
      "zone": "eu"
    },
    "cache": {
      "cpu": 1,
      "ram": 2,
      "zone": "us"
    }
  }
}
```

```terset
servers{3}:
@key	cpu	ram	zone
web	2	4	eu
db	8	32	eu
cache	1	2	us
```

### Path entries

A slash separates nested keys, so `forecast/hours` is the list `hours` inside `forecast`. Format 1.2 uses paths only when the whole document saves at least 256 UTF-8 bytes over format 1.1. A smaller document keeps the nested object as JSON.

```json
{
  "forecast": {
    "hours": [
      {
        "time": "06:00",
        "temperature": 11,
        "humidity": 82,
        "windSpeed": 9,
        "windDirection": "NW",
        "precipitation": 0
      },
      {
        "time": "09:00",
        "temperature": 14,
        "humidity": 74,
        "windSpeed": 12,
        "windDirection": "NW",
        "precipitation": 0
      },
      {
        "time": "12:00",
        "temperature": 18,
        "humidity": 61,
        "windSpeed": 15,
        "windDirection": "W",
        "precipitation": 0
      },
      {
        "time": "15:00",
        "temperature": 19,
        "humidity": 58,
        "windSpeed": 17,
        "windDirection": "W",
        "precipitation": 0.2
      },
      {
        "time": "18:00",
        "temperature": 16,
        "humidity": 67,
        "windSpeed": 11,
        "windDirection": "SW",
        "precipitation": 1.4
      },
      {
        "time": "21:00",
        "temperature": 13,
        "humidity": 79,
        "windSpeed": 8,
        "windDirection": "SW",
        "precipitation": 0.6
      }
    ]
  }
}
```

```terset
forecast/hours[6]:
time	temperature	humidity	windSpeed	windDirection	precipitation
06:00	11	82	9	NW	0
09:00	14	74	12	NW	0
12:00	18	61	15	W	0
15:00	19	58	17	W	0.2
18:00	16	67	11	SW	1.4
21:00	13	79	8	SW	0.6
```

### Scalars and escaping

Text that looks like a number, boolean or null gets JSON quotes. So do empty text and escapes.

```json
{
  "name": "Ada",
  "code": "007",
  "count": "42",
  "empty": "",
  "none": null,
  "flag": true,
  "note": "line\nbreak"
}
```

```terset
name: Ada
code: "007"
count: "42"
empty: ""
none: null
flag: true
note: "line\nbreak"
```

## API reference

Every public name in both packages. Pick a language to see its signatures, errors and examples.

`@stackdeck/terset` exports `encode`, `decode`, `rulesFor`, `RULES` and the types `JsonValue`, `JsonObject`, `JsonRoot`, `FormatVersion` and `EncodeOptions`.

`terset` exports `encode`, `decode`, `rules_for`, `RULES` and the type aliases `JsonValue`, `JsonObject`, `JsonRoot`, `JsonInputValue`, `JsonInputRoot` and `FormatVersion`.

### `encode`

Turns a JSON object or array into Terset text. For lists, the encoder uses a table only if the header and rows are shorter in UTF-8 bytes than compact JSON. The list check excludes the count line, so a tiny list table can be larger than compact JSON. A keyed map uses a table only if the complete named block, including the count line, is shorter in UTF-8 bytes than the field with compact JSON. Format 1.2 uses slash-separated path entries only when the whole document saves at least 256 UTF-8 bytes over format 1.1.

#### JavaScript

```ts
encode(value: JsonRoot, options?: EncodeOptions): string
```

Parameters:

- `value` (`JsonRoot`): A plain JSON object or array.
- `options.format` (`FormatVersion`): Defaults to `"1.2"`. Pass `"1.1"` for named cells without path entries or `"1.0"` for empty cells.

Returns: `string`: Terset text. A root array that cannot be a table is written as JSON.

Errors:

- `TypeError`: The root is not an object or array, or a value is not JSON: a class instance, a symbol key, a sparse array or a cycle.
- `TypeError`: A number is `NaN`, infinite or `-0`, or the data nests deeper than 500 levels.
- `TypeError`: `options` is not an object or `options.format` is outside the supported versions.

```js
import { encode } from "@stackdeck/terset";

console.log(encode([
  { id: "a1", name: "Ada" },
  { id: "b2", name: "Ben" },
]));
```

Output:

```text
[2]
id	name
a1	Ada
b2	Ben
```

In JavaScript: Only plain objects and arrays are accepted.

#### Python

```python
encode(value: JsonInputRoot, *, format: FormatVersion = "1.2") -> str
```

Parameters:

- `value` (`JsonInputRoot`): A `dict` or `list` of JSON values.
- `format` (`FormatVersion`): Keyword only. Defaults to `"1.2"`. Pass `"1.1"` for named cells without path entries or `"1.0"` for empty cells.

Returns: `str`: Terset text. A root list that cannot be a table is written as JSON.

Errors:

- `TypeError`: The root is not a `dict` or `list`, or a value is not JSON: another type, a key that is not a string, or a cycle.
- `TypeError`: A number is `nan`, infinite or `-0`, an `int` is not exact as a float, or the data nests deeper than 500 levels.
- `TypeError`: `format` is outside the supported versions or is passed by position.

```python
from terset import encode

print(encode([
    {"id": "a1", "name": "Ada"},
    {"id": "b2", "name": "Ben"},
]))
```

Output:

```text
[2]
id	name
a1	Ada
b2	Ben
```

In Python: Integers that a float cannot hold exactly raise `TypeError` instead of rounding.

### `decode`

Turns Terset text back into the same value, key order included. It reads the canonical text from formats 1.0, 1.1 and 1.2.

#### JavaScript

```ts
decode(text: string): JsonRoot
```

Parameters:

- `text` (`string`): Terset text, as `encode` wrote it.

Returns: `JsonRoot`: the object or array.

Errors:

- `SyntaxError`: The text is not canonical Terset, for example a wrong row or cell count.
- `TypeError`: The input is not a string.

```js
import { decode } from "@stackdeck/terset";

const value = decode("[2]\nid\tname\na1\tAda\nb2\tBen");
console.log(JSON.stringify(value));
```

Output:

```text
[{"id":"a1","name":"Ada"},{"id":"b2","name":"Ben"}]
```

In JavaScript: Rejected text throws `SyntaxError`.

#### Python

```python
decode(text: str) -> JsonRoot
```

Parameters:

- `text` (`str`): Terset text, as `encode` wrote it.

Returns: `JsonRoot`: the `dict` or `list`.

Errors:

- `ValueError`: The text is not canonical Terset, for example a wrong row or cell count.
- `TypeError`: The input is not a string.

```python
from terset import decode

value = decode("[2]\nid\tname\na1\tAda\nb2\tBen")
print(value)
```

Output:

```text
[{'id': 'a1', 'name': 'Ada'}, {'id': 'b2', 'name': 'Ben'}]
```

In Python: Rejected text raises `ValueError`. Whole numbers within `[-2**53, 2**53]` come back as `int`.

### `rulesFor` and `rules_for`

Returns the rules sentences one text needs, to send right before that text. It checks the text like `decode` does.

#### JavaScript

```ts
rulesFor(text: string): string
```

Parameters:

- `text` (`string`): Terset text, as `encode` wrote it.

Returns: `string`: only the sentences the text uses, or an empty string when none apply.

Errors:

- `SyntaxError`: The text is not canonical Terset, for example a wrong row or cell count.
- `TypeError`: The input is not a string.

```js
import { encode, rulesFor } from "@stackdeck/terset";

const text = encode({
  servers: {
    web: { cpu: 2, zone: "eu" },
    db: { cpu: 8, zone: "eu" },
    cache: { cpu: 1, zone: "us" },
  },
});
console.log(rulesFor(text));
```

Output:

```text
Tables use tab-separated headers and rows. name{N} has N entries; the @key column holds each entry's key and is not a field.
```

In JavaScript: The name is `rulesFor`, in camel case.

#### Python

```python
rules_for(text: str) -> str
```

Parameters:

- `text` (`str`): Terset text, as `encode` wrote it.

Returns: `str`: only the sentences the text uses, or an empty string when none apply.

Errors:

- `ValueError`: The text is not canonical Terset, for example a wrong row or cell count.
- `TypeError`: The input is not a string.

```python
from terset import encode, rules_for

text = encode({
    "servers": {
        "web": {"cpu": 2, "zone": "eu"},
        "db": {"cpu": 8, "zone": "eu"},
        "cache": {"cpu": 1, "zone": "us"},
    },
})
print(rules_for(text))
```

Output:

```text
Tables use tab-separated headers and rows. name{N} has N entries; the @key column holds each entry's key and is not a field.
```

In Python: The name is `rules_for`, in snake case.

### `RULES`

The full rules text, for a shared or cached system prompt that serves many texts. It is a constant, not a function.

#### JavaScript

```ts
const RULES: string
```

Parameters: none.

Returns: `string`: every rules sentence, the same in both packages.

Errors: none.

```js
import { RULES, rulesFor } from "@stackdeck/terset";

const fitted = rulesFor("[2]\nid\tname\na1\tAda\nb2\tBen");
console.log(fitted.length < RULES.length); // true, one text needs fewer rules
console.log(rulesFor("name: Ada") === ""); // true, no table means no rules
```

Output:

```text
true
true
```

In JavaScript: The same string as in Python.

#### Python

```python
RULES: str
```

Parameters: none.

Returns: `str`: every rules sentence, the same in both packages.

Errors: none.

```python
from terset import RULES, rules_for

fitted = rules_for("[2]\nid\tname\na1\tAda\nb2\tBen")
print(len(fitted) < len(RULES))  # True, one text needs fewer rules
print(rules_for("name: Ada") == "")  # True, no table means no rules
```

Output:

```text
True
True
```

In Python: The same string as in JavaScript.

### `Types`

Type names for JSON data, for code that builds or reads values.

#### JavaScript

```ts
type JsonValue = null | boolean | number | string | JsonValue[] | JsonObject;
type JsonObject = { [key: string]: JsonValue };
type JsonRoot = JsonObject | JsonValue[];
type FormatVersion = "1.0" | "1.1" | "1.2";
type EncodeOptions = { format?: FormatVersion };
```

Parameters: none.

Returns: Types only. Nothing exists at run time.

Errors: none.

```ts
import { encode } from "@stackdeck/terset";
import type { JsonRoot } from "@stackdeck/terset";

const data: JsonRoot = { team: "core", size: 3 };
console.log(encode(data));
```

Output:

```text
team: core
size: 3
```

In JavaScript: Five types, imported with `import type`.

#### Python

```python
JsonValue = None | bool | int | float | str | list[JsonValue] | dict[str, JsonValue]
JsonObject = dict[str, JsonValue]
JsonRoot = JsonObject | list[JsonValue]
JsonInputValue = None | bool | int | float | str | Sequence[JsonInputValue] | Mapping[str, JsonInputValue]
JsonInputRoot = Mapping[str, JsonInputValue] | Sequence[JsonInputValue]
FormatVersion = Literal["1.0", "1.1", "1.2"]
```

Parameters: none.

Returns: Type aliases, importable at run time.

Errors: none.

```python
from terset import JsonRoot, encode

data: JsonRoot = {"team": "core", "size": 3}
print(encode(data))
```

Output:

```text
team: core
size: 3
```

In Python: Two more aliases, `JsonInputValue` and `JsonInputRoot`, accept read-only `Mapping` and `Sequence` input.

## Rules text

For one text, send `rulesFor(text)` right before the data. The data itself carries no legend.

`rulesFor(text)` returns only the sentences that text needs. In Python it is `rules_for(text)`. It checks the text like `decode` does, so it rejects the same input.

`RULES` is the full text, for a shared or cached system prompt that serves many texts. It is the same string in both packages.

| When | The rules add |
| --- | --- |
| Any table is present | The tables sentence. |
| A table cell is empty (format 1.0 text) | The empty cells sentence. |
| A table header ends with `name=value` | The `name=value` sentence. |
| A table cell or entry value is a quoted string | The quotes sentence. |
| A table cell holds a JSON array or object | The nested cells sentence. |
| A list table starts with a bare `id` header | The `id` header sentence. |
| A keyed table `name{N}` is present | The `@key` sentence. |
| A dotted header `a.b` is present | The dotted header sentence. |
| An entry has a slash between keys, as in `a/b` | The path entry sentence. |
| None of these | Nothing. The rules are an empty string. |

The full `RULES` text:

```text
Tables use tab-separated headers and rows. Empty cells mean absent. After the header columns, a row lists its other fields as name=value. A field a row does not list is absent. JSON quotes distinguish numeric, boolean or null text from scalars. Nested cells use JSON. A leading bare id header marks string IDs. name{N} has N entries; the @key column holds each entry's key and is not a field. Header a.b is field b in object a. Key a/b is field b in object a.
```

## Errors and limits

| Call | JavaScript | Python |
| --- | --- | --- |
| encode with data that is not JSON | `TypeError` | `TypeError` |
| decode or the rules call with rejected text | `SyntaxError` | `ValueError` |
| decode or the rules call with a value that is not a string | `TypeError` | `TypeError` |

### Messages

| Message | Cause |
| --- | --- |
| Row count mismatch. | A table has more or fewer rows than its count. |
| Wrong cell count. | A row has more or fewer cells than its header. |
| Noncanonical Terset text. | No supported format version writes the value this way. |
| Maximum entry path is 8 segments. | An entry path has more than eight keys. |
| Maximum JSON depth is 500. | The data nests deeper than 500 levels. |
| Numbers must be finite and must not be negative zero. | A number is `NaN`, infinite or `-0`. |
| Cyclic JSON data. | An object or list contains itself. |
| Expected Terset text. | The input to decode is not a string. |

### Limits

| Limit | Value |
| --- | --- |
| Root | An object or an array. A bare scalar is an error. |
| JSON depth | 500 levels at most. |
| Dotted header path | 8 segments at most. Anything deeper stays JSON inside the cell. |
| Slash-separated entry path | 8 segments at most. Deeper fields stay in the last entry value. |
| Table size | Two or more records. One record stays JSON. |
| Numbers | Finite, and not negative zero. |
| Python integers | Exactly representable as a binary64 float. |

In Python, very deep data and an already deep call stack can raise `RecursionError` before the 500 level check. This depends on the stack, not the Python version.

## When not to use it

- **No lists of records.** Small config files can stay close to compact JSON. The config example uses no rules and ties compact JSON on o200k_base.
- **One-row lists.** A list needs two or more objects to become a table.
- **Mixed arrays.** A list with any item that is not an object stays JSON.
- **Lists inside rows.** A list inside a table row stays JSON in its cell. A list under an object path can have its own table.
- **Hard limits.** The root must be an object or an array. Numeric `-0` and nesting deeper than 500 levels are explicit errors.
- **Writing back.** Terset is for the model to read. Ask for answers in JSON.

## Links

- [Format spec](https://terset.dev/format): Every rule of the format, with examples.
- [Benchmark](https://terset.dev/benchmark): Token counts, answer accuracy, the method and the limits.
- [Real files](https://terset.dev/workload): Answer accuracy and input tokens on two real public files.
- [Agents](https://terset.dev/agents): Plain files an agent can read, and a prompt to paste.
- [npm](https://www.npmjs.com/package/@stackdeck/terset): The @stackdeck/terset package.
- [PyPI](https://pypi.org/project/terset/): The terset package.
