terset
Color theme

Reference for 0.4.0

Terset docs

Install, a quick start, a cheat sheet and the full API for JavaScript and Python.

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.

Implementations
LanguagePackageInstallConformance
JavaScript@stackdeck/tersetpnpm add @stackdeck/tersetPasses the 1.0, 1.1, and 1.2 suites
Pythontersetpip install tersetPasses the 1.0, 1.1, and 1.2 suites

Both packages run the shared test suites at conformance/ for 1.0, conformance/1.1/ for 1.1, and conformance/1.2/ for 1.2.

Language
Package manager
pnpm add @stackdeck/terset

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

Quick start#

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

example.mjs
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
Run it
node example.mjs
Output (the gaps are tabs)
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.

Never write Terset by hand. Always use encode.

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.

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.

Language

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

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.

Signature
encode(value: JsonRoot, options?: EncodeOptions): string

Parameters

encode parameters
NameTypeAbout
valueJsonRootA plain JSON object or array.
options.formatFormatVersionDefaults 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

encode errors
ErrorWhen
TypeErrorThe 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.
TypeErrorA number is NaN, infinite or -0, or the data nests deeper than 500 levels.
TypeErroroptions is not an object or options.format is outside the supported versions.

Example

JavaScript
import { encode } from "@stackdeck/terset";

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

In JavaScript: Only plain objects and arrays are accepted.

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.

Signature
decode(text: string): JsonRoot

Parameters

decode parameters
NameTypeAbout
textstringTerset text, as encode wrote it.

Returns

JsonRoot: the object or array.

Errors

decode errors
ErrorWhen
SyntaxErrorThe text is not canonical Terset, for example a wrong row or cell count.
TypeErrorThe input is not a string.

Example

JavaScript
import { decode } from "@stackdeck/terset";

const value = decode("[2]\nid\tname\na1\tAda\nb2\tBen");
console.log(JSON.stringify(value));
Output
[{"id":"a1","name":"Ada"},{"id":"b2","name":"Ben"}]

In JavaScript: Rejected text throws SyntaxError.

rulesFor#

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

Signature
rulesFor(text: string): string

Parameters

rulesFor parameters
NameTypeAbout
textstringTerset text, as encode wrote it.

Returns

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

Errors

rulesFor errors
ErrorWhen
SyntaxErrorThe text is not canonical Terset, for example a wrong row or cell count.
TypeErrorThe input is not a string.

Example

JavaScript
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
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.

RULES#

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

Signature
const RULES: string

Returns

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

Errors

None.

Example

JavaScript
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
true
true

In JavaScript: The same string as in Python.

Types#

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

Signature
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 };

Returns

Types only. Nothing exists at run time.

Errors

None.

Example

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

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

In JavaScript: Five types, imported with import type.

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.

What the fitted rules add
WhenThe rules add
Any table is presentThe tables sentence.
A table cell is empty (format 1.0 text)The empty cells sentence.
A table header ends with name=valueThe name=value sentence.
A table cell or entry value is a quoted stringThe quotes sentence.
A table cell holds a JSON array or objectThe nested cells sentence.
A list table starts with a bare id headerThe id header sentence.
A keyed table name{N} is presentThe @key sentence.
A dotted header a.b is presentThe dotted header sentence.
An entry has a slash between keys, as in a/bThe path entry sentence.
None of theseNothing. The rules are an empty string.
RULES
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#

Error types by call
CallJavaScriptPython
encode with data that is not JSONTypeErrorTypeError
decode or the rules call with rejected textSyntaxErrorValueError
decode or the rules call with a value that is not a stringTypeErrorTypeError

Messages

Error messages
MessageCause
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

Limits
LimitValue
RootAn object or an array. A bare scalar is an error.
JSON depth500 levels at most.
Dotted header path8 segments at most. Anything deeper stays JSON inside the cell.
Slash-separated entry path8 segments at most. Deeper fields stay in the last entry value.
Table sizeTwo or more records. One record stays JSON.
NumbersFinite, and not negative zero.
Python integersExactly 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.
  • Format spec: Every rule of the format, with examples.
  • Benchmark: Token counts, answer accuracy, the method and the limits.
  • Real files: Answer accuracy and input tokens on two real public files.
  • Agents: Plain files an agent can read, and a prompt to paste.
  • npm: The @stackdeck/terset package.
  • PyPI: The terset package.