Skip to content

TDL Library API

Moved here from the Tesserae Shell design vault on 2026-11-02. This file is now the source of truth; the vault keeps a short pointer. Names of vault notes and decisions (D1 to D94, the ADR-0014 file layout and so on) refer to that vault and are not links.

[!NOTE] The public Python API of the TDL library: repository and folder tess-dl, PyPI package tesserae-dl, import name tess_dl (ADR-0014 Shell File Language > Open Items, maintainer, 2026-11-02). The library reads TDL text into a tree that keeps everything in the file (comments, layout, positions), reports errors with file:line:column, and writes the text back unchanged except for a requested edit. It knows nothing about bars, monitors, tre, or the shell's keys. This note is a proposal for the maintainer, written so the tess-dl session can start from it. Names follow the Python standard library where a library does the same job (json, tomllib), because the maintainer asked that a person from another framework finds a familiar shape (ADR-0014 Shell File Language > Ninth-Round Decisions (2026-11-02) D68).

Purpose and Scope

  • Define the functions, classes, errors and guarantees that the shell, an editor tool and a test can rely on.
  • Out of scope, by design: checking keys and types against a schema, typing a value (a length, a colour, a boolean), reading other files for Import, evaluating <| |> slots (TEL does that), and talking to tre. All of those belong to the shell (Data Flow > Loading a Shell).
  • The library takes text, not paths: file reading, Import and the config directory are the shell's (AGENTS > 3. Layering Principle, "Data in, not files").

Where the Library Sits

flowchart LR
    T[".tdl text"] --> P["tess_dl: parse"]
    P --> D["Document tree\n(lossless, with positions)"]
    D --> S["Shell: schema check,\ntyping, Import, UIDs"]
    S --> E["TEL: compile each slot"]
    E --> M["Shell model"]
    M --> R["tre nodes and windows"]
    D -. "edit (UID)" .-> W["tess_dl: dumps"]
    W --> F[".tdl text, unchanged\nexcept the edit"]

The tree is not something tre can render. It describes the file. The shell turns it into its own model and only then into tre nodes (Layers and Components).

Behaviour

The Entry Points

Function Does Familiar from
tess_dl.loads(text, *, path=None, limits=None) Parses a string. Returns a Document. Raises TDLError on the first syntax error json.loads, tomllib.loads
tess_dl.load(fp, *, path=None, limits=None) Same, from a binary file object the caller opened (UTF-8; a byte-order mark is accepted). The library never opens a path itself tomllib.load
tess_dl.parse(text, *, path=None, limits=None) Parses and never raises for a syntax error. Returns a ParseResult(document, errors): the best tree it could build (None when the metadata or root block cannot be read, a limit stops the file or the cap is reached) and every error found, in source order, up to Limits.max_errors. For editors and for the shell's "collect every error, then stop" rule ast.parse (but tolerant)
tess_dl.dumps(document) Returns the text of a document. For a document from loads, the result is exactly the input, byte for byte json.dumps
tess_dl.dump(document, fp) Writes that text to a binary file object json.dump

path is a label for error messages (Top_Bar_Module.tdl). It is never opened.

Errors

One base class, TDLError, with a subclass TDLSyntaxError. Every error has:

Field Meaning
code A stable slug such as tdl-unclosed-block (TDL Language > Errors, D52)
message One sentence saying what is wrong, in plain words
hint What to write instead
origin An Origin: file, line, column (both 1-based), and end_line, end_column, offset
related Other Origins the error mentions; a duplicate key names both places

str(error) is file:line:column: message (hint). The message follows the wording rules in Wording and Familiar Names. The error list is the one in TDL Language > Errors: the 17 accepted in D52, tdl-unexpected-text (G13) and four limit and input codes (tdl-too-large, tdl-too-deep, tdl-unsupported-version, tdl-bad-encoding, G18), all accepted by the maintainer on 2026-11-02, 22 in all.

[!NOTE] The suffix check is the shell's (maintainer, 2026-11-02, D91) The library does not look at file names. Comparing the root block with the suffix (_Shell.tdl, _Module.tdl) is done by the shell, or by Tesserae UI for its own types, and the shell's error is shell-root-suffix. The library keeps 18 language errors and four limit and input codes (22 in all).

Limits

tess_dl.Limits(max_bytes=1_048_576, max_errors=50, max_depth=64). All three are decided: 1 MiB and 50 errors (Validation and Errors > Parsing) and depth 64, counting the root block as 1 (G11). A file over a limit stops with tdl-too-large or, for depth, tdl-too-deep. TEL uses a Limits class the same way.

The Tree

All classes are importable from tess_dl. Nodes are immutable: they can be shared between threads, and an edit makes a new document.

Class Fields Notes
Document metadata, root, path, text, language_version text is the source
Metadata mapping from key to Value; origin Keeps unknown keys. Reading is by key: doc.metadata["Name"]
Block type, entries, origin, name type is the word before the brace. name is the value of Name: or None
Property key, value, key_origin, value_origin Key: value
If condition: Slot, body, else_body (or None), origin If <| c |> { } Else { }
For variables: tuple[str, ...] (and variable, the first), items: Slot, key: Slot, body, name, origin For x In <| xs |> Key <| x.id |> { }, For i, x In <| enumerate(xs) |> Key <| x.id |> { }
Comment text, origin A # comment, kept where it stands

Block.entries holds Property, Block, If, For and Comment in source order. Helpers: Block.properties (a mapping by key; a repeated key is an error, D9), Block.blocks (child blocks only), Block.get(key, default=None), Block.walk() (every descendant), and Document.find("Shell_Root.Main.Top_Bar") (a dotted path of Name: values, D28).

Index paths (G35). Many blocks have no Name: (Shadow, Border, Children), and a node belongs to the document it was read from, so a program that keeps a selection across edits needs another address. Block.index_path (also on If and For) is the tuple of entry indexes from the root block: () is the root, (2,) is its third entry, (2, 0) is the first entry of that. Inside an If the indexes count its body and then its else_body; inside a For, its body. Document.at(index_path) returns the Block, If or For at a path, in any document, so after an edit new_doc.at(path) is the same place. It raises IndexError for an index out of range and ValueError for a path that goes through or ends at a property or a comment. A node built in code has the path (), which means nothing.

Children is an ordinary block named Children; Import: file is an ordinary property. Document.imports() lists the names so the shell does not search for them, and the library does not open them.

Values

The library gives each value a lexical kind and the text it came from. It does not decide what the text means; that is the schema's job in the shell (a proposal, Open Questions 1).

Class Written as Fields
Word TOP, true, Top_Bar, Battery (unquoted) text. Booleans, null and enums are words until the schema types them (D2, D33)
String "..." or '...' value (escapes resolved), text (as written)
Number 16, -4, 0.9 value (int or float), text
Percent 50% value (int), text
Call rgba(0 0 0 0.5) name, args (values separated by spaces)
List [a, b, c] items
Slot <| expression |> text (what is between the delimiters), text_origin (where that text starts, for TEL), origin
Template Battery <| battery.percent |>% parts: strings and Slots, in order

A value that is exactly one slot is a Slot; text with a slot inside is a Template, matching the rule in TDL Language > Values.

Slot.text_origin is built to be handed to TEL. The library does not import TEL. The shell converts: tess_el.Origin(file=o.file, line=o.line, column=o.column).

Editing

A document never changes in place. An edit returns a new Document whose text equals the old text with one change.

Call Does
document.with_metadata(key, value) Sets a metadata key. A new UID goes directly after the last version line (TDL or Shell, D10, G24); any other new key goes just before the closing ---; an existing key changes only its value. value is plain text: a bare word when it reads back the same, else a quoted string (G32)
document.without_metadata(key) Removes the whole line of a metadata key; unchanged if the key is absent
block.with_property(key, value) Sets a property and returns the new Document. value is the TDL text of one value on one line. An existing property changes only its value; a new one goes on a line after the last property with that property's indentation and line ending, or inline in a block written on one line (G24, G32)
document.replace(start, end, text) Replaces document.text[start:end] (character offsets) and reparses; the escape hatch
document.find(path) The block at a dotted path of Name: values; the first name is the file's own Name and stands for the root block. Raises KeyError if there is none (D28, G32)
block.without_property(key) Removes a property. On its own line it goes with the whole line, including a comment at the end of that line; sharing a line, it goes with one separating comma. KeyError if there is none (G35)
block.with_child(block_text, index=None) Returns (Document, Block): the new document and the block just added. block_text is the TDL of exactly one block, on one or several lines; it is re-indented to its neighbours and takes their line ending, or goes inline in a block written on one line. index is a position in block.entries, as for list.insert: all kinds of entry count, 0 is first, None is last. An index that points at a comment at the end of a line is moved past it, so the block never lands between an entry and its own comment; read the real place from the returned block's index_path. Errors in block_text are TDLSyntaxErrors whose origins are inside block_text (file <block_text>). IndexError for an index out of range (G35)
block.without_child(child) Removes a child block, If or For: child is a node taken from this block's entries or its index there. The entry goes with its lines and with a comment at the end of its closing line; comment lines above it stay. ValueError for a node that is not an entry of this block (a node of an older Document is not), a property or a comment; IndexError for an index out of range (G35)
block.move_child(child, to) Moves a child to index to of the new entries (as for list.insert after list.pop), re-indented to its new neighbours, with a comment at the end of its closing line. A move to where the entry already is returns an equal document. ValueError as for without_child, and for an entry that shares a line with another and spans lines (use without_child and with_child); IndexError for to out of range (G35)
if_node.with_condition(slot_text) Replaces the condition of an If (the <| … |> after If) and returns the new Document. slot_text is the slot as written in a file, delimiters included ("<| battery.low |>"); space around it is ignored and the inside is kept byte for byte. Only the bytes of the old condition change, every other byte stays and every index_path stays valid (G37)
for_node.with_items(slot_text) The same for the list slot after In (For x In <| items |>)
for_node.with_key(slot_text) The same for the slot after Key
for_node.with_variable(names) Replaces the loop variables in the declaration: a name, "i, item" or a sequence of names, written back as a, b. It does not rename references: x inside <| x.id |> stays, because a slot is opaque text to this library (renaming inside an expression needs TEL). ValueError if a name is not a key (a letter, then letters, digits and _), is reserved (If, Else, For, In, Key), is repeated, or there is none

These four are on the If or For node, which you get from Document.at(index_path) or from block.entries. Errors: invalid slot syntax is a TDLSyntaxError whose origins are inside slot_text (origin.file is <slot_text>, line 1 is the text's first line); valid TDL that is not exactly one slot ("word", "<| a |> b", "<| a |>, B: 1", "<| a |> # c"), an invalid or reserved variable name, and a node built in code are ValueError. The reread result is checked: the node at the same index path must read exactly as the edit says, with its body unchanged, or the edit is refused.

An Else stays addressable. An If's index_path steps count its body entries (a comment at the end of the If line is the first of them) and then its else_body entries, so the block Y in If <| c |> { X { } } Else { Y { } } is (i, 2) when the body holds two entries, and every edit above works on a block, If or For at such a path (doc.at((1, 2)).with_property(...), doc.at((1, 3)).with_condition(...)). Adding or removing an Else as a unit, changing a block's type word and renaming a property's key are not edits in this release.

Every edit keeps comments, blank lines, indentation and the order of everything it did not touch (this is what the UID write needs; R-06 in Risk Register). An edit that would make the file invalid raises TDLError and returns nothing. A call that is wrong whatever the file holds (a key that is not a name, a reserved word as a property key, a value that is not one value, a span outside the text, a block built in code) raises ValueError. Edits reread the result with the default Limits. The four block edits also check the reread result: the block must hold exactly its old entries plus or minus the one named, and an edit that would change anything else is refused with ValueError.

Formatting

Call Does
tess_dl.format_block(text) The canonical layout of one block, as a string without a trailing line ending. text is the TDL of exactly one block, as for Block.with_child; comment lines above or below it are kept. Errors are TDLSyntaxErrors with origins inside text
tess_dl.format(document) A new Document whose text is in the canonical layout. Raises TDLSyntaxError for a document with errors (read it with loads, not parse)

The canonical layout (G36). Two spaces per level, never a tab. One entry per line: no , between entries and no entries sharing a line. A block with no entries is Type { } on one line. If … { … } Else { … } has } Else { on one line, unless there are comments between the } and the Else, which then stay on their own lines between them. For x In <| items |> Key <| key |> { has single spaces. Key: value has one space after the colon. A comment on its own line stays on its own line at the new indentation; a comment at the end of a line stays at the end of that line, after two spaces. Values, slots, strings and comments are written exactly as they were, and a value that spans lines (a list) keeps its inner layout, re-based to the new indentation. Where the source had one or more blank lines between two things, there is one; none at the start or end of a block. In a document the metadata block is written the same way, a comment or blank lines between it and the root block are kept (one blank line at most), and so are comment lines after the root block. The whole text uses the line ending of its first line, a leading byte-order mark stays, and the text ends with one line ending.

Both are idempotent: formatting a result again changes nothing. The result is reread and must have the same content (canonical()) and the same comments as the input; if it would not, ValueError is raised and nothing is returned. Node positions change, but the entries and their index paths do not: format never adds, removes or reorders an entry. Formatting a tree built in code is not in this release (open question 3).

Plain Data View

document.to_data() and block.to_data() return plain dicts, lists and strings, with no comments or positions, for tools and tests that only need the content. The shape is the library's first-slice decision. The tree is the main API; this is a convenience.

Building a Tree in Code

The Python builder (Python Builder) must produce the same tree as the parser, so the nodes can be constructed directly: Block("Bar", [Property("Edge", Word("TOP"))]). A constructed node has no position. tess_dl.dumps formats a constructed tree with the library's standard layout (two-space indent). node.canonical() returns a normalised plain structure with trivia and positions dropped, so a parity test compares two trees by ==. Names follow TEL's canonical (Expression Language Requirements > TEL 0.1.0 Released (2026-11-02)). The formatter for text and documents is built (Formatting); formatting a tree built in code waits until a program builds trees.

Wording and Familiar Names

The maintainer's rule (2026-11-02): the names and the prose are for people from the UI design world, who expect a thing to behave as it does in another framework. In this library that means:

  • Function names come from json and tomllib (loads, load, dumps, dump), and node names from the file's own words (Block, Property, Comment), not from compiler jargon (Token, Production, Lexeme stay private).
  • An error message says what happened in one plain sentence and the hint says what to write. It names the thing the author wrote, not the parser state: "This colour needs quotes. Write "#ffffff"." and not "unexpected token HASH".
  • The language reference in tess-dl explains each construct with a short example before any rule, and says where TDL behaves differently from CSS, QML or Flutter (Familiar Names Audit when written).

Configuration

None. The only inputs are the arguments above and the Limits.

Python Contract

Item Value
Import import tess_dl; every public name is in tess_dl.__all__
Version tess_dl.__version__ (package) and tess_dl.LANGUAGE_VERSION ("0.2"); a file with a newer major version raises tdl-unsupported-version
Python 3.14 or later; no runtime dependencies (maintainer, 2026-11-02)
Typing Fully typed; ships py.typed
Threads Pure functions on immutable data: safe to call from any thread; the shell may parse on the watcher thread and hand the Document to the loop with call_soon (Process Model and Threading)
Stability Before 1.0, a minor version may change the API; every change is listed in the changelog and in a TDL-REQ-### when the shell asks for it (AGENTS > 6. Requests Between Projects)
Private Anything not in __all__, and the whole lexer

Integration

  • The shell calls tess_dl.parse for every file at load, collects the errors, then walks the tree with its schema (Validation and Errors).
  • The shell calls document.with_metadata("UID", uuid) and writes the result with its own file code when it registers a file (Config Discovery and Registry).
  • TEL receives slot.text and an origin built from slot.text_origin; the shell adds nothing to the position because a slot sits on one line (Validation and Errors).
  • A TextMate grammar and any later editor tool use tess_dl.parse and the codes.

Design

None. This is a library without a user interface. The language it reads is designed in TDL Language and, after the move, in the tess-dl repository.

Accessibility

Error messages are plain sentences that a screen reader reads whole: no colour or symbol carries meaning, and the position is in text (file:line:column).

Performance Budget

  • Parsing is one pass over the text. Budget: a 100 KB file in under 20 ms and a file at the 1 MiB limit in under 250 ms. Measured on 2026-11-03 (Python 3.14.8, AMD Ryzen AI 9 HX 370): 13.1 ms and 140.3 ms, growing linearly; no adversarial input is super-linear. The tree the reader keeps is about 19 times the size of the text. The figures, the method and the command are in benchmarks.md; Performance Budgets in the vault holds the ledger.
  • loads of the same text twice gives equal documents; a cache is the shell's business (a warm cache keys on the file's hash, as the schema cache does).
  • The library allocates no thread and no timer.

Failure Modes and Recovery

Failure Result
Invalid UTF-8 in load TDLSyntaxError tdl-bad-encoding, with the byte offset
Syntax error loads raises at the first one it meets; parse records it and carries on (G31, TDL Language > Errors): a bad entry is skipped to the end of its line or the } that closes its block
More than 50 errors The list stops at the limit, the last entry says The list stops at 50 errors., and nothing more is read
An edit would break the file TDLError; the original document is untouched
A newer language version tdl-unsupported-version, with the library's version in the message

Open Questions

  1. [x] Values stay lexical (maintainer, 2026-11-02, "yes", D74). The reasoning was: the library returns Word, String, Number, Percent, Call, List, Slot and Template, and the schema in the shell types them. The alternative is for the library to know lengths and colours, which makes it carry shell meaning.
  2. [x] The suffix check is the shell's, as shell-root-suffix (maintainer, 2026-11-02, D91).
  3. [ ] Whether canonical() on a tree built in code, dumps of such a tree and the Python builder are in a release. The formatter for text (format_block) and for documents (format) is built (G36).
  4. [ ] The shape of to_data().
  5. [x] The extra codes tdl-unsupported-version, tdl-too-large, tdl-too-deep and tdl-bad-encoding are accepted (maintainer, 2026-11-02, G18), with tdl-unexpected-text (G13).
  6. [ ] A tdl command (tdl check file.tdl, tdl format) for authors and editors: recommended after the first release, not in it.
  7. [ ] Build tooling and CI for tess-dl (the TEL project's choices are the starting point).

Acceptance Criteria

  • [x] tess_dl.dumps(tess_dl.loads(text)) == text for every file in the conformance corpus (comments, blank lines, indentation, a final newline or none). Tests: test_corpus.py::test_ok_case_round_trips_byte_for_byte (54 files), test_roundtrip.py (generated files).
  • [x] The 22 error codes each have a corpus file that raises it with the stated line and column. Tests: test_corpus_files.py::test_every_code_has_a_case, test_corpus.py::test_error_case_loads_raises_the_first_listed_error and ..._load_raises_the_same_first_error; tdl-too-large and tdl-too-deep are built in test_limits.py.
  • [x] Width 32 raises tdl-unexpected-text, pointing at the first character that does not fit. Tests: corpus case errors/unexpected-text-no-colon; test_acceptance.py.
  • [x] tess_dl.parse on a file with six deliberate mistakes returns six errors with the right positions (JSON Schema and Editor Support). Test: corpus case errors/six-mistakes through test_error_case_parse_lists_every_listed_error.
  • [x] with_metadata("UID", x) puts UID directly after the last version field and changes no other byte. Tests: corpus cases edits/uid-after-last-version, uid-after-tdl-only; test_edits.py (one changed span, generated files).
  • [x] Color: #fff raises tdl-bare-hash; Color: "#fff" # note is a String and a Comment. Tests: test_acceptance.py; corpus cases errors/bare-hash, strings/hash-and-comment.
  • [x] Text: <| max(a, b) |> is one Slot with text max(a, b); <| '|>' |> ends at the second |>; <| {'a': {'b': 1|> |> is one slot. Tests: test_acceptance.py; corpus cases slots/one-slot, slots/quoted-close, slots/nested-braces.
  • [x] |> where two blocks close is two closing braces; the old <| |> slot form is refused with a hint to <| |>. Tests: test_acceptance.py; corpus cases blocks/close-adjacent, errors/unexpected-text-old-slot.
  • [x] A file at 1 MiB parses within the budget; one byte over raises tdl-too-large. Tests: test_limits.py (exact size, one byte more, growth ratio); the measured time is in benchmarks.md.
  • [x] Importing tess_dl imports no other third-party package, and tess_dl.__all__ lists every public name. Tests: test_acceptance.py (a clean interpreter with -I, and the list of public names).
  • [ ] A tree built in code and the same file parsed give equal canonical() results. Not in 0.1: building a tree in code, the formatter and canonical() on such a tree wait for open question 3 (G26); canonical() on a parsed document is in 0.1.
  • 42 Python API · ADR-0014 Shell File Language · TDL Language · Python Builder · Validation and Errors · Data Flow · Risk Register