SyncTERM embeds Wren in three isolated scripting hosts. A persistent trusted VM owns the main menu, a second persistent VM owns the file picker, and every connection gets a fresh restricted VM which is torn down at disconnect. Connected scripts hook into keyboard, mouse, inbound bytes, outbound bytes, status text, and a periodic timer; menu scripts implement the dialing directory and settings UI; and picker scripts implement the local-file consent interface. Each host exposes a different set of capabilities.

This document is the reference for that scripting layer: how scripts are discovered, how the embedded scripts can be overridden, and the complete add-on object model.

Why Wren

Wren is a small, class-based, dynamically typed scripting language. Three properties make it a good fit for SyncTERM:

  • It compiles to bytecode in-process; no separate toolchain or external interpreter is required.

  • The VM is a few thousand lines of plain C with no external dependencies, vendored under wren_vm/.

  • The host program controls every binding the script can reach. No filesystem, networking, or process primitives leak in by default.

The full upstream language reference lives at https://wren.io/. This manual covers only the SyncTERM additions.

Quick Start

The minimal "hello world" hook prints a message to the SyncTERM Wren console the first time you press F1 while connected:

import "syncterm" for Hook, Key

Hook.onKey { |k|
  if (k == Key.f1) {
    System.print("hello from wren!")
    return true        // consume the keystroke
  }
  return false         // pass through to SyncTERM
}

Save this as hello.wren in the SyncTERM scripts directory (see Script Loading), connect to any BBS, and press F1. In a graphical or native-console backend, open the console with Ctrl+`. In ANSI or ncurses mode, press Ctrl+S and choose Wren Console from the Online Menu.

Wren Language Reference

A compact reference for the Wren syntax SyncTERM scripts use. Full upstream documentation at https://wren.io/. Key facts up front: Wren is single-threaded and cooperative (concurrency via fibers, no threads); whitespace-significant (newline terminates statements; no ; token); class-based with single inheritance; dynamically typed.

Comments

// Line comment.
/* Block comment, /* nested */ blocks ok. */

Literals

true false

Booleans.

null

The single null value.

123 0xFF 1.5e3

Numbers. All numeric values are 64-bit floats; 0x for hex; underscores 1_000_000 for digit grouping.

"hello"

String literal. Escapes: \\ \" \% \0 \a \b \e \f \n \r \t \v \xNN \uNNNN \UNNNNNNNN.

"got %(x)"

String interpolation: %(expr) evaluates expr and inserts its toString. A bare % not followed by ( is a lex error — see Strings and %.

[1, 2, 3]

List literal.

{"a": 1, "b": 2}

Map literal.

1..5

Closed Range (1, 2, 3, 4, 5 — includes 5).

1...5

Half-open Range (1, 2, 3, 4 — excludes 5).

Statement Termination

Newlines separate statements. There is no ; token at all. Two statements on one line is a compile error. This trips up developers coming from C / JS / Python regularly.

var x = 1                  // ok
var x = 1 ; var y = 2      // ERROR: Invalid character ';'

Two consequences of the same rule:

  • Ternaries can’t span lines. cond ? a : b must be on one line — the then-branch terminates at a newline before the :.

  • else after a newline-ended if body is a syntax error. if (c) body whose body sits on the same line as the if ends at the newline; an else on the next line is orphaned. Either brace each branch (so else follows }) or put the whole chain on one line.

if (a == "x") foo() else bar()      // single-line, ok
if (a == "x") {                     // braced, ok
  foo()
} else {
  bar()
}
if (a == "x") foo()                 // ERROR: 'else' is orphaned
else bar()

Strings and %

The Wren lexer treats % inside a "…​" string as the start of an interpolation %(expr). A % not followed by ( is a lex error — not a literal %. To put a literal percent sign in a string, escape it as \%:

"100%"          // ERROR: Expect '(' after '%'.
"100\%"         // ok — four bytes: 1, 0, 0, %
"got %(x)"      // ok — interpolation, inserts x.toString

Every literal % needs a leading \. The pair \% is its own escape — \\% does not work, because \\ consumes the slash on its own and leaves a bare %; spell that as \\\%.

Variables

var x = 1                  // declare and initialize
x = 2                      // reassign

Block-scoped (everything between { and }). Shadowing in inner scopes is allowed. Top-level var at module scope is a module-level binding (importable from other modules). Declaration is required before use; there is no auto-vivification.

Operators

Arithmetic: + - * / % (modulo follows the dividend’s sign), unary - and +. Comparison: < ⇐ > >= == !=. Logical: && || ! — short-circuit, return one of their operands (not coerced to Bool). Bitwise: & | ^ << >> ~ — operate on integers (Wren truncates to 32-bit for the bitwise op). Range: .. and .... Conditional: cond ? a : b (one line). Type test: obj is Class.

The .. / ... operators bind tighter than method calls, so write (0...list.count) not 0...list.count when chaining.

Control Flow

if (cond) {
  ...
} else if (cond2) {
  ...
} else {
  ...
}

while (cond) {
  ...
}

for (item in iterable) {
  ...
}

break        // exit innermost loop
continue     // next iteration
return v     // return from method/function

for (x in seq) {} works on anything implementing iterate(prev) and iteratorValue(iter) — Lists, Maps (yields MapEntry objects), Strings (yields codepoint substrings), Ranges, and your own classes.

Functions and Closures

Wren has no top-level function keyword. Functions are closures created with Fn.new:

var add = Fn.new {|a, b| a + b }
var n   = add.call(3, 4)            // 7

var greet = Fn.new {
  System.print("hi")
}
greet.call()

Block syntax { …​ } after a method name passes a closure as the last argument:

list.map {|x| x * 2 }        // map(_) takes a Fn

Single-line { expr } returns expr implicitly; multi-line bodies return null unless an explicit return is hit. This applies uniformly to Fn.new, Fiber.new, getters, methods, and operator overloads. The inverse is also true: { return expr } on a single line is a compile error — single-line bodies are expression-mode, and return is a statement.

foo() { 42 }                 // ok — implicit return
foo() {                      // multi-line — last expression NOT returned
  var x = 1
  x + 1                      // discarded; foo() returns null
}
foo() {                      // ok — explicit return
  var x = 1
  return x + 1
}
foo() { return 42 }          // ERROR: single-line, return not allowed

Classes

Single inheritance, no abstract classes, no interfaces. All fields are private to the declaring class (see "Field scope" below).

class Animal {
  construct new(name) {
    _name = name
  }

  name { _name }                          // getter
  name=(s) { _name = s }                  // setter

  speak() {                               // method
    System.print("%(_name) makes a sound")
  }

  static kingdom { "Animalia" }           // static getter
  static spawn(n)  { Animal.new(n) }      // static method

  // Operators: + - * / % - (prefix) ! < > <= >= == [_] [_]=(_)
  +(other) { _name + other.name }
}

class Dog is Animal {
  construct new(name, breed) {
    super(name)                           // call super constructor
    _breed = breed
  }

  speak() {                               // override
    System.print("%(name) barks")
  }

  describe() {
    super.speak()                         // call super method
    System.print("It's a %(_breed)")
  }
}

Field scope

Field references (_name, __static) resolve against the class currently being compiled, not the inheritance chain. A subclass' _x is a brand-new slot, not the parent’s _x. Cross class boundaries via getters/setters:

class Widget {
  construct new() { _surface = null }
  surface { _surface }                    // expose to subclasses
}
class Pane is Widget {
  paint() {
    var s = surface                       // ok — uses getter
    var t = _surface                      // BUG: brand-new field, null
  }
}

Symptom of getting it wrong: Null does not implement 'X(,)' errors from subclass methods reading "the parent’s" field.

Naming

  • _name — instance field. Only legal inside a class body; the parser rejects it elsewhere.

  • __name — static field. Same scoping rule.

  • name_ (trailing underscore) — convention for "class-private" methods. Not enforced by the language; a strong project hint.

Foreign methods and classes

foreign declarations bind to host C code:

class Codepage {
  foreign static encodes_(s)              // host-implemented static
  foreign instance_method(arg)            // host-implemented instance
}

foreign class Cell {                      // host owns instance allocation
  foreign ch
  foreign ch=(s)
}

A class needs foreign class only when the host allocates instance data; a plain class with foreign static methods is fine for namespace-style bindings (see Codepage, Hook).

Type checks

obj is Class returns true if Class is in the object’s class chain. Compiles to obj.is(Class). You can override is, but you cannot delegate to the default via super.is(c) — is is a reserved keyword and super. requires an identifier after it. Override only if the foreign genuinely implements every method of the claimed class.

Fibers

Fibers are first-class coroutines. Wren is single-threaded and cooperative; concurrency comes from yielding fibers, not threads. There is no await, no Promise, no scheduler — the fiber handle IS the resumption token.

var f = Fiber.new {
  System.print("a")
  Fiber.yield()                  // suspend; control returns to .call() caller
  System.print("b")
}
f.call()                          // prints "a", returns when fiber yields
f.call()                          // prints "b", fiber finishes

// .yield(v) returns v from the .call() that resumed the fiber:
var g = Fiber.new {
  while (true) {
    var x = Fiber.yield(42)       // yield 42, get next call's arg as x
    System.print(x)
  }
}
g.call()                          // returns 42
g.call("hi")                      // prints "hi", returns 42
g.call("yo")                      // prints "yo", returns 42

// .try() catches abort:
var h = Fiber.new { Fiber.abort("boom") }
var err = h.try()                 // err == "boom"; h.error == "boom"

Fiber.yield(v) transfers to the immediate .call() caller — a child fiber yielding inside a hook body returns control to the hook body, NOT up to the dispatcher. This is what makes Fiber.new { …​ }.call() from inside a hook safe.

For host-driven async: a foreign method captures Fiber.current from a slot and returns; the host arranges to call .call(_) on the captured handle later. See Modal Input for the canonical example.

Modules and Imports

import "module"                   // load module, no symbols imported
import "module" for Name          // import a single symbol
import "module" for A, B, C       // multiple
import "module" for Name as Alias // rename on import

Module names are strings; the host resolves them. In SyncTERM, modules are looked up first in the root user script directory, then in the active event’s user script directory, and finally in the matching embedded scripts. A user file myhelper.wren in the script directory is importable as import "myhelper" and overrides an embedded module with the same name.

Common Pitfalls

A checklist of mistakes that catch every new Wren author at least once. Most are consequences of rules above; this section gives them a single place to look up.

  • Semicolons. Wren has no ;. Every separator is a newline.

  • Multi-line bodies don’t auto-return. Use explicit return.

  • Single-line { return x } is a syntax error. Drop return.

  • Ternaries on one line only. Split via if/else or pre-compute.

  • else must follow } on the same line, or chain on one line.

  • Every literal % in a string needs \%. Bare % starts interpolation. See Strings and %.

  • Subclass _field is NOT the parent’s. Use getters/setters.

  • String.count is codepoints; s[i] and s[a...b] are bytes. Mixing them silently truncates UTF-8 strings. For byte iteration use s.bytes.count.

  • String < > ⇐ >= are not defined. list.sort() on strings aborts; pass an explicit byte-wise comparator.

  • Wren modulo follows the dividend’s sign. -1 % 5 is -1, not 4. For positive-modulo, write ((x % n) + n) % n.

  • foreign class is for instance allocation only. Use plain class with foreign static for namespace bindings.

  • No async / await / scheduler. Use fibers and Fiber.yield.

Wren Standard Library

The built-in classes Wren provides without any host bindings. These are always available, no import needed. Many are mixin-aware via the Sequence protocol, so iteration and transformation methods work on Lists, Maps, Ranges, Strings, and your own classes that implement iterate / iteratorValue.

System

Static-only namespace for I/O and timing.

System.print()

Print a blank line.

System.print(value)

Print value.toString followed by newline.

System.printAll(seq)

Print each item in seq, one per line.

System.write(value)

Print value.toString, no newline.

System.writeAll(seq)

Like printAll without newlines.

System.clock

Process CPU time reported by C clock(), in seconds as Num; not elapsed wall time.

Note
In SyncTERM, System.print / System.write are routed to the Wren console log buffer (visible via the Wren Console pane), not to the process’s stdout. Use Host.print(s) when you need output to reach the launching shell. Compile errors, reported runtime errors and stack traces go to both the Wren console and the process’s stderr.

Object

Root of every class hierarchy. Every value responds to:

obj == other

Identity by default; classes can override.

obj != other

Negation of ==.

obj.hash

Hash code, integer.

obj.is(class)

Type check; same as obj is class.

obj.toString

Default returns "instance of <Class>". Override for nicer output.

obj.type

Returns the object’s class.

!obj

Boolean negation. Falsy values are false and null only — every other value (including 0 and "") is truthy.

Class

The class of all classes. Useful properties:

Cls.name

String name of the class.

Cls.supertype

Parent class, or null when Cls is Object.

Cls.toString

The class name.

Bool

true and false. Has toString (returns "true" / "false") and the standard ! && || operators (the latter two short- circuit and return one of the operands, not a coerced Bool).

Null

The single value null. !null is true; everything else (null.toString, null == null) does what you’d expect.

Num

All numeric values are 64-bit floats. No separate integer type; the language calls something an "integer" when it has no fractional part. Mathematical method-style helpers:

Num.pi

π.

Num.infinity

+∞.

Num.largest, Num.smallest

Max / min finite double.

Num.maxSafeInteger, Num.minSafeInteger

Range of exact-integer doubles (±2⁵³−1).

n.abs

Absolute value.

n.ceil, n.floor, n.round, n.truncate

Round-modes.

n.sqrt

Square root.

n.sin, n.cos, n.tan

Trig (radians).

n.asin, n.acos, n.atan

Inverse trig.

n.atan(x)

atan2(self, x).

n.log, n.log2, n.exp

Natural log, log base 2, eˣ.

n.pow(p)

nᵖ.

n.min(other), n.max(other)

Pairwise min / max.

n.clamp(lo, hi)

Clamp into [lo, hi].

n.fraction

Fractional part.

n.sign

-1 / 0 / +1.

n.isInteger, n.isInfinity, n.isNan

Predicates.

n.toString

Decimal string.

n & m, n | m, n ^ m, ~n

Bitwise (truncated to 32-bit).

n << k, n >> k

Bit shifts (also 32-bit).

Native integer limits

Native integer quantities exposed as Numbers use the inclusive exact range Num.minSafeInteger through Num.maxSafeInteger (−9,007,199,254,740,991 through 9,007,199,254,740,991). Unsigned quantities, including file sizes, byte counts and offsets, start at zero. Fractions, NaN, infinity and values outside the range abort before native work starts; representable values above this range, including 2^53 itself, are rejected. Counts must also fit the host’s size_t, and narrower protocol or API limits still apply. SFTP v3 read counts and set-mtime values are bounded by 4,294,967,295. An offset may exceed 32 bits even on a 32-bit host.

Formatting helpers such as Format.bytes deliberately accept estimates and retain their documented rounding/saturation rules.

Native results are checked before conversion. File.size, File.offset and File.mtime return FileError with IOErr.outOfRange and errno zero when the native result cannot be represented. SFTP stat/directory operations complete with a non-transient SFTPError (IO_ERROR_OUT_OF_RANGE) if any size or timestamp is outside the range; they never return rounded or partial metadata. Other integer getters, including profile timestamps, picker metadata, transfer byte counts and log sequence numbers, abort on overflow. Continuous measurements such as elapsed fractional seconds remain Numbers.

The persistent transfer queue applies the same bounds to saved sizes, resume offsets, timestamps and IDs. It preserves an invalid queue for inspection and refuses to run it. Job IDs reserve the largest safe integer as the exhausted next-ID value, preventing rounded or reused IDs.

String

Immutable byte string with UTF-8-aware operations. Strings can contain malformed UTF-8 and embedded NULs. For well-formed UTF-8, s.count counts Unicode scalars, while s[i], ranges, and s.codePoints[i] use byte offsets. Use s.bytes for bytes and s.codePoints.toList or s.toList for scalar-ordinal indexing. Unicode scalars are not grapheme clusters; Text.graphemes supplies that separate operation.

s.count

Scalar count for valid UTF-8; does not validate the string.

s.isEmpty

True iff count == 0.

s.bytes

A Sequence view yielding each byte as a Num.

s.codePoints

A Sequence view yielding each codepoint as a Num.

s[i]

Codepoint substring starting at byte index i. If i is mid-codepoint, returns the raw byte.

s[a..b], s[a...b]

Visit byte offsets in the range, expanding complete scalars at lead bytes. Negative indices count from the end.

s + other

Concatenation.

s.indexOf(needle)

Byte index of first match, or -1.

s.indexOf(needle, start)

Byte index of match at-or-after start.

s.contains(needle)

Substring presence.

s.startsWith(prefix)

Prefix check.

s.endsWith(suffix)

Suffix check.

s.replace(old, new)

All non-overlapping occurrences.

s.split(separator)

List of substrings, separator removed.

s.trim(), s.trimStart(), s.trimEnd()

Strip whitespace.

s.trim(chars), s.trimStart(chars), s.trimEnd(chars)

Strip any chars in the supplied string.

s.iterate(prev), s.iteratorValue(iter)

Sequence protocol: yields one codepoint substring per step.

s.toString

The string itself.

String.fromByte(n)

Single-byte string.

String.fromCodePoint(cp)

Encode a codepoint as UTF-8 string.

The codePoints view’s subscript still takes a byte offset; only materializing it into a List changes the index unit. A subscript into a continuation byte returns a raw byte String, while codePoints[i] returns -1 there. Ranges are neither raw byte slices nor scalar-ordinal slices: "é"[0…​1] returns the whole two-byte character, while "é"[1…​2] returns "".

No implicit NFC normalization occurs. "é" and "e\u0301" are different Strings, with scalar counts 1 and 2. A one-byte invalid String can also have count == 1, so text-taking native bindings must validate UTF-8 using the explicit byte length rather than a String count or C strlen.

List

Mutable, ordered, dynamic-length, heterogeneous.

List.new()

Empty list.

List.filled(size, value)

Pre-fill size copies of value.

[a, b, c]

Literal.

list.count

Length.

list.isEmpty

True iff empty.

list[i], list[i] = v

Access / replace; negatives count from the end.

list[a..b], list[a...b]

Slice (returns a new List).

list.add(v)

Append.

list.addAll(seq)

Append every item of seq.

list.insert(i, v)

Insert v at index i.

list.remove(v)

Remove and return the first occurrence; returns null if absent.

list.removeAt(i)

Remove and return element at i.

list.clear()

Empty the list.

list.indexOf(v)

Index of first match, or -1.

list.contains(v)

Membership.

list.sort()

In-place sort with <. Aborts on Strings (no < defined) — pass a comparator.

list.sort {|a, b| a < b }

In-place sort with a custom comparator.

list.swap(i, j)

In-place swap.

list.iterate(prev), list.iteratorValue(iter)

Sequence protocol.

list.toString

"[a, b, c]".

Map

Mutable hash map. Keys may be any hashable value (Num, String, Bool, Null, Range, or Class — not List, Map, or arbitrary instance). Iteration yields MapEntry objects with key and value properties; use m.keys when only keys are wanted.

Map.new()

Empty map.

{"a": 1, "b": 2}

Literal.

m.count

Number of pairs.

m.isEmpty

Empty?

m[k], m[k] = v

Access / set. Missing key returns null.

m.containsKey(k)

Distinguishes "missing" from "value is null".

m.remove(k)

Remove and return the old value (or null).

m.clear()

Empty the map.

m.keys, m.values

Sequence views (lazy).

m.iterate(prev), m.iteratorValue(iter)

Sequence protocol; iterating yields MapEntry objects.

m.toString

"{a: 1, b: 2}".

Range

Created via the .. (inclusive) and ... (exclusive-end) operators on Nums. Lazy — values are produced on iteration.

r.from

Lower bound.

r.to

Upper bound.

r.min, r.max

Bounds normalised regardless of direction.

r.isInclusive

True for .., false for ....

r.count

Number of values.

for (i in r) {}

Iterate.

Reverse ranges are valid: 5..0 walks 5, 4, 3, 2, 1, 0, while 5...0 excludes the ending zero.

Sequence (mixin)

The base "iterable" protocol. Sequence itself isn’t usually instantiated; List, Map, Range, String, and your own classes that implement iterate(prev) and iteratorValue(iter) inherit its methods. Most are lazy where it makes sense.

seq.all { fn }

True iff fn(item) is truthy for every item.

seq.any { fn }

True iff any item passes.

seq.contains(value)

Membership via ==.

seq.count

Eager count.

seq.count { fn }

Items where fn(item) is truthy.

seq.each { fn }

Apply fn for side-effects.

seq.isEmpty

True iff count == 0.

seq.join()

Concatenate all items' toString.

seq.join(sep)

…with sep between consecutive items.

seq.map { fn }

Lazy mapped sequence.

seq.where { fn }

Lazy filtered sequence.

seq.skip(n), seq.take(n)

Lazy.

seq.reduce { |a, b| …​ }

Fold from first item.

seq.reduce(seed) { |a, b| }

Fold from seed.

seq.toList

Materialise into a List.

Fiber

First-class coroutines.

Fiber.new { …​ }

Create a paused fiber whose body is the closure.

Fiber.current

The fiber currently running.

f.call(), f.call(value)

Resume f; the value is the return of the most recent Fiber.yield inside f.

f.transfer(), f.transfer(value)

Like call, but does not record this fiber as the resumer; cannot be returned to via Fiber.yield.

f.transferError(err)

Resume f with err raised inside it.

f.try(), f.try(value)

Like call, but if f aborts the abort is caught and f.error is set.

f.isDone

True after the body returns or aborts.

f.error

The abort message if try caught one, else null.

Fiber.yield()

Suspend; control returns to the most recent .call() caller.

Fiber.yield(value)

…passing value as the return of that .call().

Fiber.abort(err)

Raise err in the current fiber. Caller’s .try() catches it.

A yield ends the current call/try boundary. To catch an error after a later resume, use try() for that resume too. Fiber.suspend() returns to the host while retaining the ordinary caller chain; transfer and transferError retain their standard Wren behavior.

Host UI/resource wrappers drive their own callback fibers with ordinary try() calls on each resume. Native completions are delivered to those registered drivers; direct Fiber calls are not redirected. This is a host callback policy, not an extension to Wren’s Fiber primitives.

Fn

A callable closure. Fn.new { …​ } is the only constructor.

Fn.new { …​ }

Build from a closure literal.

f.call()

Invoke with no args.

f.call(a, b, …​)

Invoke with args (up to 16).

f.arity

Declared parameter count.

Script Loading

Script Directory

User scripts live in a per-platform directory. SyncTERM creates the directory on first launch if it doesn’t already exist.

Platform Scripts directory

Linux / *BSD

$XDG_DATA_HOME/syncterm/scripts/
(default ~/.local/share/syncterm/scripts/)

macOS

~/Library/Application Support/SyncTERM/scripts/

Windows

%APPDATA%\SyncTERM\scripts\

Haiku

~/config/settings/SyncTERM/scripts/

The directory has two roles, distinguished by where files live within it:

Path Role

scripts/<name>.wren

Importable module. Loaded when something imports it via import "<name>", or when a personal directory entry explicitly lists it as a per-connection script. Put reusable libraries and selectively loaded connection scripts here.

scripts/auto/<event>/<name>.wren

Auto-loaded entry script. Runs at the moment the framework fires <event>. menu runs once in the persistent main-menu VM; picker runs once in the persistent file-picker VM; and connected runs once in each connected-session VM.

Files anywhere else under scripts/ (e.g. user-organised subdirectories of pure library code) are reached only via import — the framework owns scripts/auto/ and ignores everything else for auto-load and per-connection selection purposes.

Module Names

Each script becomes its own Wren module, named after the file basename without the .wren extension and without any directory prefix. myscript.wren becomes module myscript, whether it’s at scripts/myscript.wren or scripts/auto/connected/myscript.wren. Module names are how scripts cross-reference each other:

import "myscript" for SomeClass

Module names are also how the embedded-script override mechanism works (see below).

Embedded Scripts

SyncTERM ships with a small set of scripts compiled into the binary. They are not stored as files; the build system runs wren_embed_gen at compile time, infers each script’s role from its source path (library vs auto-load, and which event for auto-load), and folds the sources into a C string table linked alongside wren_host.c.

The currently embedded scripts are:

Module Role Purpose

syncterm

library

Foundational module: foreign-class declarations and Wren-side helpers (REPL, Key, Color, Codepage, …). Loads on first import. The menu VM binds only its trusted UI subset; calling any other declared capability aborts the calling fiber.

syncterm_menu

library / menu only

Trusted main-menu data model: transactional BBS-list loading and editable DirectoryEntry records, program settings, web lists, and custom-font configuration. The connected loader rejects this module.

syncterm_picker

library / picker only

Request-scoped file-picker interface. It exposes directory listings, path resolution, metadata, and completion methods, but no file-open capability. Menu and connected scripts cannot import it.

picker_bootstrap

reserved library / picker only

Host-controlled picker entry and recovery surface. SyncTERM always interprets its embedded copy before loading picker overrides.

file_picker

auto / picker

Split-pane file and directory browser. It implements single-file, directory, save, and cross-directory multi-file selection and exports FilePicker.run(request) as the picker host entry point.

console

auto / connected

Connected-session Ctrl+` hook for graphical and native-console backends. ANSI and ncurses sessions reach the shared wren_console implementation through the Ctrl+S Online Menu instead.

wren_console

library

Wren REPL UI shared by the connected and menu VMs. Each invocation reads the log belonging to its current VM.

connected

auto / connected

Alt+L send-login handler. Sends username, password, and sysop password from the directory entry, with the right send-order rules per connection type.

keys_default

auto / connected

Default Hook.onKey bindings corresponding to the in-terminal hot-key commands in term.c’s input loop: Alt+X / Alt+H and — ANSI/ncurses only — Ctrl+Q route to `DisconnectFlow.run; Alt+O toggles mouse-event reporting; Alt+Up / Alt+Down walk the network throttle rate; Shift+Insert pastes from the clipboard. With remote mouse tracking off or locally disabled, left-drag selects text to copy and middle- or right-click pastes. X10 tracking retains local drag selection but sends button clicks to the remote; other tracking modes leave the gestures to the remote. Alt+B opens the scrollback viewer; Alt+C delegates to CaptureMenu.run; Alt+M delegates to MusicMenu.run; Alt+V opens SessionLogView.run.

disconnect_flow

auto / connected

DisconnectFlow.run(exitApp) — modal "Disconnect…​ Are you sure?" Confirm popup shared by the Alt+X / Alt+H / Ctrl+Q hooks in keys_default. On Yes calls Conn.endSession(exitApp). Imported by keys_default; not used by online_menu (the menu selection is itself the confirmation).

capture_menu

auto / connected

CaptureMenu.run() — Wren implementation of the capture_control contract (capture type / save path / pause / resume / close). Driven by Alt+C in keys_default and the "Capture Control" entry in online_menu.

music_menu

auto / connected

MusicMenu.run() — Wren implementation of the music_control contract (ANSI music mode picker). Driven by Alt+M in keys_default and the "ANSI Music Control" entry in online_menu.

session_log

auto / connected

SessionLogView.run() — current-session diagnostic viewer, reached by Alt+V or View Session Log in the Online Menu. Opens at the newest record; arrows, PageUp/PageDown, Home/End, and the mouse wheel scroll the snapshot. Long records wrap, and log text is displayed literally. Escape returns to the terminal with its screen and input state restored.

online_menu

auto / connected

OnlineMenu.run() — the SyncTERM "Online Menu" reached via Alt+Z, plus Ctrl+S in ANSI/ncurses modes. Lists the in-terminal control commands and dispatches the selection back into the primitives that drive the individual hot-keys (Conn.scrollback, Conn.upload, Conn.download, CaptureMenu.run, MusicMenu.run, …​). The Output Rate and Log Level entries chain into a sub-list before closing, and the Wren Console entry opens the connected VM’s REPL. View Session Log opens the same diagnostic viewer as Alt+V. Disconnect / Exit selections call Conn.endSession directly — no Confirm popup, since selecting the entry IS the confirmation.

status_default

auto / connected

Default Status.callable — paints the terminal’s bottom row. See Status for the API and override pattern.

main_menu

auto / menu

The persistent Wren main-menu controller. It loads the menu BBS model, prompts for an encrypted-directory password when necessary, and presents the classic dialing directory: the directory and SyncTERM Settings lists remain visible together, the active list uses the configured Classic Theme palette, and the selected entry’s comment and list commands occupy the bottom two rows. The host calls MainMenu.run(currentName, connected) whenever the application is offline or Alt+E enters the directory over a connected session. The connected form highlights the active entry and reuses the offline directory’s scroll position, centering the entry if it is outside that viewport or no offline position exists. Browsing the connected directory preserves the offline bookmark used when the session ends. The controller binds Ctrl+` to the menu VM’s REPL in graphical and native-console backends, and Ctrl+Q in ANSI and ncurses modes. It displays that VM’s unread-log indicator in the top-right corner. The offline form owns the classic light-shade application background and title/time row; the connected form leaves the saved terminal screen behind its panes.

menu_host_ui

auto / menu

Internal controller used by C connection and startup code for trusted alerts, confirmations, prompts, choices, and progress overlays. An override must preserve the MenuHostUI static method contract described below. Connected scripts cannot import this menu-only module.

The syncterm module is loaded on demand the first time something imports it. Its top level obtains host-created Cache and Download objects where that VM has them. The auto-load embeds run when their owning VM is created: once per application for menu and picker, and once per BBS session for connected.

Built-in main interfaces

Main Interface selects Classic or Retro: in Classic it is under Program Settings, and in Retro it is on Settings → Program. Classic remains the default when MainUI is absent or unrecognized. The accepted choice is stored as MainUI=Classic or MainUI=Retro under [SyncTERM] and takes effect when Settings closes, without restarting or reconnecting. It selects both the offline directory and the existing edit-only connected directory. Custom main_menu script overrides retain precedence over this built-in choice. The legacy MainUI=DOS spelling remains readable; saves use MainUI=Retro. The layout and selected colour theme are independent.

Retro opens on a full-width calling table. Its fixed 45-cell Name column fits the longest legal name under the 30-scalar / 60-byte UTF-8 limits, including wide characters. Address uses the remaining space; Port, Type, Term/Graphics, Encoding, Calls, and Last Call appear as space permits. At 80 columns the table shows Name, Address, Port, and Type. Narrow screens pan the table with Left/Right instead of shrinking or truncating the Name column. Term/Graphics describes the saved emulation and enabled graphics, such as ANSI/RIP1, ANSI/RIP3, ANSI/Sky1.3, ANSI/Sky3.1, VT52/IGS, or ANSI/BIG; it does not report live protocol negotiation or use the advertised TERM string as an emulator name. The last-call date uses local time. Long text is clipped on grapheme boundaries.

Up/Down and paging keys select entries; type-to-search and Ctrl-F/Ctrl-G retain the usual list behavior, with Retro Find also matching connection columns. Enter connects offline and edits while connected. F2 edits, Insert adds, Delete removes, F5/F6 copy/paste, Ctrl-S manages sorting, and </> cycle sort profiles. A single mouse click selects a directory row; double-click activates it. The selected entry’s comment is centred below the table, above the clickable bottom command bar, with the same full-line styling and long-text clipping as Classic. Entries without comments leave that line blank. F4 opens the separate Settings screen. Tab moves between the directory and command bar; Left/Right choose a focused command and Enter runs it. Escape exits the directory or returns to the existing session. Opening, resizing, or switching the directory does not resize the remote terminal.

Retro Settings opens one tabbed book with five categories on one row at 80 columns: Program (general behavior and audio/MIDI), Connections (new-entry defaults, modem, security, shell and TLS), Appearance (colours, themes, fonts and display), Files (list path, web lists and file locations), and About (read-only build capabilities and licenses). Regular settings edit directly in the book. Resource editors return to the tab that opened them; Escape from a child returns one level. Pending book edits survive child editors, including theme selection. Build information stays inside About instead of opening another menu. Resource managers and the defaults editor retain their own acceptance rules; the book’s Save/Cancel controls apply to its program-settings draft.

Resource list selectors, sorting and Wren scripts use full-page framed lists with bottom command hints. At 80 columns or wider, a separate scrollable information panel shows help or preview details. Narrow screens retain F1 help. Tab moves between the list and Back. Escape or Back returns to the owning tab or screen. Classic retains its compact menus.

Retro entry settings and New Connection Defaults use separate full-page forms. They share the Settings book’s tab and field controls. Entry settings have three tabs on one row at 80 columns: Connection (including login and security), Terminal (including scripts and palette), and Files & Notes (paths, logging, and comment). New Connection Defaults uses the same grouping without the per-entry comment, naming its last tab Files. The active category stays highlighted and bracketed in the top tab row while keyboard focus moves through its fields. Click a tab or use Ctrl-PageUp/PageDown to change categories. Tab/Shift-Tab move between three control groups: the tab bar, form fields, and Save/Cancel. Entering the tab bar focuses the current page. Home/End jump to the first/last tab. Arrow keys move within each group; Left/Right stay on the same row, and Up/Down stay in the same field column. Text editors retain cursor movement; at either end, Left/Right can cross to an adjacent field column. tab.selected styles the current page independently of tab.focused for keyboard focus; tab.selected.focused styles the combined state. Brackets mark the current tab and > marks keyboard focus, including when colours match. Labels sit beside their controls; text and number editors retain shaded, bracketed rectangles when unfocused. Text boxes fit their field limits, numeric boxes fit their minimum/maximum representation, and enum boxes fit their longest choice, all capped by the available column width. Manage actions are compact buttons sized to their labels; read-only facts are not editable boxes. Enum fields have a down-arrow marker and open an attached dropdown with Enter, Space, Alt-Down, or a click. The list opens below the field, or above when space is limited. It expands to show all choices or fill the available height on that side; a scrollbar appears only when the choices still do not fit. Arrows, paging keys, Home/End, and typing navigate choices. Enter or a click accepts; Tab accepts and moves to the next control group. Escape or an outside click cancels without changing the draft. Resizing keeps the list attached, or closes it if the field moves out of view. Opening a dropdown retains the form’s active colours. Wide screens balance fields across two columns. PageUp/PageDown and the Previous/Next controls beside the tabs reach overflow fields within the current category on small screens. F1 opens contextual help. Specialized palette, script, font, and file selectors remain available. Edits stay in a private draft across page changes and resizing. Save/F10 accepts the complete draft; Cancel/Escape asks before discarding changed drafts. A failed save retains the form and its draft for retry. In safe mode, allowed program changes use Apply without persistence; existing directory write restrictions still apply. Existing native partial-effect errors, such as a saved configuration followed by a runtime-application failure, are reported without claiming that completed effects were rolled back.

Classic retains its two-pane layout, field-list editors, immediate application of accepted program fields, and existing Escape/save conventions.

Overriding Embedded Scripts

A user script whose basename and role match an embedded module overrides the embedded one. The shared REPL implementation can be replaced with ~/.local/share/syncterm/scripts/wren_console.wren; all three VMs import that library when their built-in menu, connected, or picker entry point opens the console. Replacing scripts/auto/connected/console.wren changes only the connected graphical/native-console Ctrl+` hook. Replacing scripts/auto/menu/main_menu.wren changes the menu key binding along with the rest of the main-menu controller. Replacing scripts/auto/picker/file_picker.wren changes the picker implementation but not its reserved recovery surface.

The check is an exact match on the bare module name within the same script role. A root console.wren is a library module distinct from the connected auto-load module, while a root wren_console.wren replaces the shared library. Case matters: Wren_Console.wren is a different module from wren_console.wren.

To opt out of an embedded auto-load script entirely, drop a stub override into the matching directory:

// ~/.local/share/syncterm/scripts/auto/connected/connected.wren
// Disable the default Alt+L handler.

The override is loaded but registers no hook, so Alt+L silently does nothing.

Load Order

  1. scripts/auto/<event>/ is enumerated for files with the exact lowercase .wren suffix.

  2. Each embedded script tagged with the firing event runs, unless its module name appears in the user-script set.

  3. Each user script in scripts/auto/<event>/ runs as its own filename-derived module in case-sensitive byte order. This phase runs the user override omitted from the preceding embedded phase. A module already loaded through an earlier import is skipped.

  4. For connected, root modules selected by the active personal directory entry run in their stored order. A module already loaded by an earlier script or import is skipped because Wren modules execute only once per VM.

  5. A command-line -W script runs last in the connected VM.

import statements (whether from a script’s top-level or inside its body) resolve through the lookup chain for the current VM:

  1. scripts/<name>.wren — importable root module.

  2. scripts/auto/<event>/<name>.wren — where <event> is menu, connected, or picker; this catches imports of auto-load modules which have not run yet.

  3. The embedded table — built-in fallback by module name.

The foundational syncterm module lazily loads the first time anything imports it; subsequent imports hit Wren’s module cache.

The menu host attempts every menu auto-load module and refuses to start a partly initialized menu if any of them cannot be read or interpreted. Picker implementation modules are optional: their errors are logged while the embedded picker bootstrap and recovery surface remain available. A missing FilePicker class enters recovery when the picker is invoked.

Per-Connection Scripts

A personal directory entry may contain an ordered WrenScripts INI value:

[Example BBS]
WrenScripts = session_logger,custom_keys

Each value names scripts/<name>.wren; do not include a path or extension. Names contain only ASCII letters, digits, and underscore, are at most 255 bytes, and are case-sensitive Wren module names. The menu does not offer a module already present in the entry, and the host removes exact duplicates assigned through the menu API. syncterm_menu, syncterm_picker, and picker_bootstrap are reserved and cannot be selected.

The editor catalog is rebuilt from root user-script files with the exact lowercase .wren suffix on each request, in case-sensitive byte order. It does not include modules embedded in the executable. Files with invalid module names and the three reserved names above are omitted.

The entry editor’s Wren Scripts row opens the ordered-list editor. Select the blank final row or press Insert to add a root module; Delete removes one. Enter tags the selected module, Up and Down move it, and Enter places it. Escape while moving restores its original position. A configured module whose file is no longer present remains visible as [Missing] so opening and saving the entry does not silently discard it.

Only personal named entries load this field. Defaults, installed system entries, web-list entries, and quick-connect records cannot activate scripts. At connection time, an unreadable configured module is reported in the connected VM log and error indicator, and loading continues with the next configured module.

A script’s top-level code runs once in the VM which owns its event. Top-level code commonly registers hooks or creates the long-lived menu controller; persistent state should be stored on classes (static fields).

The built-in main_menu module is also the host entry-point contract. An override must export class MainMenu with these static methods:

  • prepare() loads the directory, performs any password interaction, and returns a Bool indicating whether the model is ready.

  • run(currentName, connected) presents the directory. currentName is a String or null. When connected is false, return a current DirectoryEntry or Profile to start that connection or null to exit. Connected invocations are edit-only; their return value is ignored.

  • offerSave(source, name) receives a detached Profile and a separate suggested entry name after an unsaved quick-connect or command-line connection ends, including a return to the directory via Alt-H, and returns whether it was saved. The host calls prepare() first, then copies the C record into menu storage; no connection-owned pointer or foreign value is passed into Wren.

Additional trusted auto/menu scripts can extend the shipped controller without replacing it:

import "syncterm" for Mod
import "main_menu" for MainMenu

MainMenu.registerCommand(121, Mod.command, "Alt-Y", "Open an offline planner",
    Fn.new {|app, connected| Planner.show(app) })

registerCommand(key, modifiers, keyName, description, callback) replaces an earlier extension on the same key/modifier pair or appends a new one. The overload without modifiers uses zero. Registration happens during menu-VM startup, before MainMenu.run builds its controller. The callback receives the running App and the connected-directory Bool, is suppressed while another modal is open, and its key name and description are appended to the directory help.

When the built-in module is loaded, it paints the main-menu background and title bar immediately. Startup alerts and progress panes therefore appear over initialized menu chrome before MainMenu.run() constructs the interactive directory.

The host validates and copies a record returned by run while the menu VM is still selected, so the Wren foreign object itself never crosses into the connected VM.

For an independently packaged frontend using this override contract, see Modern UI. Its directory/settings scripts are installed into the user script directory and are not embedded in SyncTERM.

The shipped controller binds Ctrl+` to the menu VM’s REPL in graphical and native-console backends, and Ctrl+Q in ANSI and ncurses modes. A CP437 ‼ in the top-right corner reports unread output from that VM: yellow for print output and red for errors. Synchronous key and mouse handlers run through an error boundary; an abort is added to the menu VM’s log, the indicator is refreshed, and the main menu continues running. This boundary does not hide layout or painting failures, which still abort MainMenu.run rather than repeatedly failing during every redraw.

The Classic controller defines the following main-menu interaction contract. The Retro presentation shares its directory operations and host entry point, with the navigation and draft-editing differences described in Built-in main interfaces. After a connection or failed connection attempt, the offline directory restores its selected entry and viewport rather than returning to the first row. The selection follows the entry’s name across reloads and sort changes; if that entry disappeared, the previous row is retained and clamped to the new list. Connected-directory editing keeps a separate bookmark and does not overwrite the offline return position. Viewports are clamped when the list or screen size changes so the selected row remains visible.

Tab from the directory enters the selected entry’s comment field, then advances to the simultaneously visible settings pane; Backtab traverses the same path in reverse. Left and Right move directly between the directory and settings. The first completed left click in an inactive pane transfers focus without activating a row; a second click activates the row. A wheel event moves the active list regardless of which pane is under the pointer. A completed left click on the main-screen background transfers focus to the other pane. Enter connects (or edits while connected) from the directory and invokes one settings action from the settings pane. F2/Ctrl-E, Insert, Delete, F5/F6, Ctrl-S, </>, Ctrl-D, and Alt-B invoke their documented commands. F2 does nothing on the blank append row; Ctrl-E invokes the row’s add operation. The comment row is also clickable for direct editing. An override may present the model differently while preserving the host entry-point and ownership contracts.

The comment is edited only in the main screen’s footer. It is not a field in the full directory-entry editor. F1 and Ctrl-Z in the footer display the directory help. Operation-specific alerts and confirmations display the context help for the operation which opened them.

The footer advertises edit, copy, paste, insert, and delete only while the directory pane owns focus. The SyncTERM Settings pane advertises only Help and Exit, matching the operations available from that pane. While a comment is being edited, the footer shows the hints for the pane that opened it.

Lists which support appending provide a selectable blank final row. Activating the blank row or pressing Insert invokes the same add operation. The shipped directory, sort-profile, sort-field, web-list, custom-font, and short-palette editors expose both forms; the palette row is omitted once all sixteen colors are present. + aliases Insert, while - and ASCII DEL alias Delete. Ctrl-Insert aliases F5 Copy, Shift-Insert aliases F6 Paste, and Shift-Delete invokes Cut where that operation is available. Backspace and a right click alias Escape after the focused widget declines the event. Delete and the editor-specific copy, paste, rename, and cut keys are direct list commands.

Adding a directory entry prompts for its name, connection type, and address, then writes it immediately and returns to the directory. A single :port suffix is accepted for network addresses. F2 or Ctrl-E opens the full entry editor. Editing a read-only entry first offers to create a personal entry with the same name. F5/F6 prompts for a new name when pasting a personal entry; pasting a copied read-only entry uses the copied name.

The specialized editors provide direct menu operations. Enter on a sort profile opens its field list, and Enter on a sort field reverses that field; [ and ] move between profiles without returning to the profile list. Enter on a web list edits its URI. Font details are a flat Name plus four cell-size paths, and selecting a path opens the picker directly. The encryption screen has distinct Change Password, algorithm, and Decrypt operations; changing algorithms reuses the password already held by the host. Palette editing uses a combined RGB, HSV, and hexadecimal colour picker. The RGB ramps accept exact decimal entry, every ramp supports keyboard and mouse adjustment, and the contrast grid selects the foreground/background pair shown in the sample. % restores the mode default; Enter accepts the colour and Escape cancels it.

In safe mode, accepted default-entry and web-list changes update the in-memory model but are not written to configuration files. Encryption conversions are no-ops; Change Password presents its password prompt before returning.

When an action rebuilds a repeating editor’s list, the editor retains the same row and viewport position. This applies to entry logging and palettes, sort profiles and fields, program settings and their nested lists, web lists, and font management. Directory editing commands apply only while the directory pane owns focus. Directory, pasted-entry, command-line-save, sort-profile, and web-list name prompts repeat after an invalid or duplicate name. Entry-editor prompts distinguish empty, reserved, and duplicate names. Directory add and command-line-save prompts treat an empty edit as cancellation while still distinguishing reserved and duplicate names; an entry creation failure is reported separately. Sort-profile field navigation returns to the last profile visited. New entries are inserted according to the active sort profile after their connection details are accepted. Quick Connect limits the directory address field to 64 characters. Current Screen Mode and Startup Screen Mode use distinct dialog titles and context help. When PromptSave is enabled, every unsaved quick-connect or command-line session offers to save its complete entry after disconnect. Accepted SSH host keys remain in the temporary profile until that entry is saved; host-key verification updates only existing personal entries and preserves their list encryption. Directory password and system-password rows are obscured in the editor list, but selecting one uses ordinary text editing so the existing value can be inspected and corrected. Personal-directory encryption prompts are masked. Rate choices select the first supported rate at or above a configured value, or Current when no supported rate is high enough. An OS window-close request sets a sticky process-exit latch. It does not ask the main menu or connected session for confirmation. An App unwinds nested widgets through their normal Escape path one modal frame at a time, allowing each Wren call to return and run its normal cleanup. A widget explicitly marked atExit remains interactive; the command-line directory-entry save workflow uses this for its confirmation, prompts, errors, and editor. Accepted Classic Theme colour changes rebuild the active theme immediately while Classic Theme is selected. A selected file theme is unaffected. Renaming a persisted entry also renames its per-entry cache directory after the directory file is written successfully. Font Management treats an empty name as cancellation when adding a record. Otherwise, it accepts the entered name and the file returned by the picker as the record values. It reports a full custom-font table before prompting for another name. The preformatted File Locations and Build Options viewers use the titles File Locations and Build Options. Their maximum dimensions are 78 by 21 and 60 by 21 cells respectively, capped to preserve the standard modal margins and complete drop shadow. Their Markdown content defines the label emphasis, indentation, and section layout rendered by the shared Help viewer. Palette Insert is exposed only while the palette has room for another color, and Delete is exposed only while a color can be deleted. Sort-profile Paste is exposed only after Copy or Cut has supplied a clipboard profile. Font Details and the outer Font Management list both support Insert, Delete, and the blank add row. Adding a web list skips its initial fetch when no cache path is available but records the configuration; explicit refresh reports the missing cache. Left and Right move directly between the directory and settings panes. Leaving the comment field by mouse, pane navigation, or application exit commits the accepted edit before focus moves. The entry editor reselects its highlighted field after [ and ] move between entries. Program Settings summarizes enabled audio backends, and entry rows distinguish automatic terminal types, unset passwords, and nonzero communication rates. Web-list edits update the in-memory configuration immediately and are written when the Web Lists screen closes. Saving an existing directory entry does not change its Added timestamp. Clearing the Terminal Type field writes the empty override, so a subsequent directory reload uses automatic terminal-type selection. In the palette component editor, % resets all three components of the selected colour from the mode palette without moving focus to another field. Creating or copying a personal entry with the same name as a read-only entry replaces that row immediately. The model stores the read-only entry beneath the personal override. Deleting the override exposes the read-only entry; renaming and saving the personal entry exposes the read-only entry under its own name. Adding an entry may create such an override. Pasting a copied personal entry instead requires a name unique across all currently visible entries.

The inactive directory comment is centered across its line. While the directory pane has focus, its selection supplies the OS window title; while the settings pane has focus, the title is the bare SyncTERM version. Editing a comment leaves the title from the pane where editing began until focus moves again. The active editor is left-aligned within the middle screen width - 4 cells. Its existing value initially appears selected in the text-input lightbar, so typing or deleting replaces the complete comment. Cursor movement or mouse positioning leaves the value unchanged and switches to the normal menu colors for ordinary editing. Leaving the editor immediately centers the inactive row, even when its value was unchanged.

The shipped menu keeps context help beside the Wren screen that owns each control. Directory, sort-profile, entry-editor, settings, web-list, font, and encryption panes assign Markdown helpText to their panes and nested dialogs. F1 therefore resolves to the general screen description from the list and to field-specific help while a choice or prompt is open. Menu overrides should use the normal Help Markdown contract described under Help viewer. Help content must be Markdown; legacy help-buffer markup is unsupported.

The shipped editors distinguish accepting an edit from writing its backing file. A confirmed entry field immediately updates the entry-backed Profile view, and a confirmed program setting is immediately applied to the running settings. Their files are written when the owning entry or Program Settings editor closes. Font changes stay in the font model until Font Management closes. Sort-profile operations update the working profile model, which is written when Sort Profiles closes; profile cycling from the main directory writes immediately. None of these screens exposes the persistence boundary as a selectable Save or Cancel row.

Escape from a nested prompt or choice cancels only that nested operation. Escape from an owning editor closes it without rolling back accepted edits. An owning menu stays on the modal stack and is rendered behind a nested prompt, picker, viewer, or submenu until that child is dismissed.

Headless Tests

The CMake test suite drives menu and picker VMs against headless consoles and isolated temporary data trees. After building a configured tree, run the Wren tests with:

ctest --test-dir build --output-on-failure -R '^(wren_|st_wren_)'

The wren_host test covers the shared host bindings. The wren_* tests run the menu, picker, and individual UI-script suites through the same embedded module loader used by the application. The current tree does not provide a standalone source-tree connected-VM script runner.

VM Lifetimes and Trust Boundaries

SyncTERM deliberately uses three Wren VMs. They do not share Wren objects, handles, modules, globals, hooks, timers, result queues, or foreign objects.

The persistent menu and picker VMs each own a logical console. A VM’s normal UI and its REPL share that console rather than copying the screen into a separate REPL console. Their cells, fonts, palette, cursor, dimensions, and pending input remain independent while one physical display switches synchronously between them. Work on the inactive console remains off-screen until it is selected. The connected terminal still uses the existing screen-ownership path pending its migration to the same display model.

  • The menu VM is created once after conio and configuration are initialized. It owns scripts/auto/menu/, survives connections, is parked while the connected screen is active, and is destroyed at application shutdown. It can edit the BBS list and settings and can request a picker operation.

  • A fresh connected VM is created by wren_host_init(bbs) for each BBS session and freed by wren_host_shutdown() on every exit path. It owns scripts/auto/connected/. Module statics, hooks, timers, claims, and queued results do not survive disconnect.

  • The picker VM is created once after the menu VM, owns scripts/auto/picker/, and remains parked except while a picker request is active. It cannot import syncterm_menu, inspect BBS records, change settings, establish connections, or open files. Its request object exposes only directory listings, path resolution and metadata, and one-shot completion methods.

The remote system is considered hostile. A remotely supplied script may know the active entry’s username, password, and system password; those values are already meaningful to that remote. It must not gain the authority to enumerate or edit other BBS entries, change global settings, start another connection, or mint arbitrary local-file access. Consequently syncterm_menu is not merely omitted from the connected documentation: the connected loader explicitly rejects it, and menu foreign objects cannot cross the VM boundary.

Menu auto-script overrides are trusted application code, not a sandbox for downloaded scripts. In addition to directory and settings mutation, the menu VM can invoke picker-mediated local-file operations, open URLs from the completed session’s scrollback, and update trusted application chrome. Do not install a remotely supplied script under scripts/auto/menu/; remote or otherwise untrusted session automation belongs in the per-connection VM and receives only that VM’s capabilities.

Connected scripts intentionally retain Input.ungetKey, Input.ungetMouse, physical-key synthesis, and the other synthetic input bindings. User scripts need them to automate the current remote session. Isolation is provided by the VM and transition barriers, not by removing those session-local controls.

At every ownership transition (connect, disconnect, entry to or return from the menu through Alt+E, and entry to or return from the picker), the host establishes a new input epoch. It discards pending conio keyboard and mouse pushback and rejects late input-shaped results tagged with an older epoch. Input claims remain parked in the VM that owns them and cannot run while another VM owns the screen. This prevents a connected script from placing synthetic input in ungetkey() / ungetmouse() just before the trusted menu or picker takes control. The same barrier protects the connected VM when control returns from a trusted UI. Physical-key production is suspended while the menu owns input, restored when returning to a live connection, and disabled with its held-key state cleared when the connection ends.

The picker VM is the local-file consent broker. Neither its caller nor the picker script receives arbitrary pathname-open authority. A single-file or multi-file completion is converted by C into read-only File handles. A save completion explicitly reports create or overwrite consent; C converts it into a one-shot write-only grant without retesting the pathname. These rights remain attached to the foreign File handle as documented in Write consent. The request object is invalidated as soon as the picker returns, so it cannot retain listing or completion authority between calls.

Picker overrides under scripts/auto/picker/ are trusted local application code, but the picker VM still receives only the capabilities needed by the browser. The host always interprets the embedded picker_bootstrap first. A picker implementation compile or runtime failure therefore enters a recovery screen instead of terminating SyncTERM: Ctrl+` opens the picker VM’s REPL, Escape cancels the request, and Key.quit exits the application. The normal picker shows that VM’s unread or error indicator at the top right and uses the same Ctrl+` binding. Only failure to initialize the VM or reserved bootstrap disables picker operations.

C-owned startup and connection flows also render their dialogs through the persistent menu VM. These calls do not expose a dialog capability to connected scripts. Blocking alerts, confirmations, prompts, and choices save and restore the current screen and establish input barriers both before and after the dialog, so synthetic connected-session input cannot answer a trusted question. Progress overlays deliberately do not clear or claim input: connection setup continues polling conio so the user can abort a stalled operation. Clearing progress restores the exact screen, palette, fonts, video flags, and cursor state saved when the first update was shown.

The embedded menu_host_ui module exports class MenuHostUI with static methods alert(title, message), alertWithHelp(title, message, helpText), help(title, body), confirm(title, message), prompt(title, message, initial, maxLen, masked), choice(title, message, options, current), ripChoice(title, message, options, hotkeys, required), status(title, lines), and statusClear(), plus disconnected(title, details) for the post-session bottom-row notice. That notice keeps the completed terminal visible until Enter, with F1 opening session details and the final protocol log. Alt-B (Cmd-B on macOS) opens that session’s scrollback; Escape returns to the notice. If the connection had a status bar, its row stays blank in the disconnected style outside the viewer’s content area. With the status bar disabled, the viewer uses the full terminal height, including the bottom row. Without a status bar, the terminal scrolls once to make room for the notice. History is saved before that scroll, so opening scrollback reconstructs the completed screen apart from its scrollback indicators. Terminal dimensions and status layout are preserved, and the notice does not enter saved history. hidePopups and local hangup/exit skip the notice. This is a host-controller ABI rather than a public menu script API: application C code holds the call handles and invokes it.

ripChoice is the C-owned RIP pick-list bridge: hotkeys are Unicode scalar values (zero disables one), and required lists ignore Escape and outside clicks. Closing the application still unwinds the dialog and restores its saved screen.

The progress pane fits the wider of its title and status rows, capped to the standard screen margins. The pane itself is centered, but all status rows share one padded left edge so preformatted columns remain aligned between rows. Text wraps within that common content width on narrower screens. Menu auto-script overrides are trusted and may replace its presentation, but must keep those signatures and return Bool, String/null, and numeric choice indexes as appropriate or host dialogs fail closed.

Every reconnect rebuilds the connected VM from scratch. Connected scripts needing cross-session state must persist it through an authorized Cache / Download file or picker token. Menu scripts can keep ordinary Wren state for the application lifetime, but durable changes still require the explicit model save methods.

Console entries, cached entry handles, REPL state, and unread markers belong to one VM. Opening the menu through Alt+E therefore shows the menu VM’s log, not output produced by the parked connected VM, and no console object or handle crosses the trust boundary.

The owner thread is captured at init; dispatchers called from any other thread (background SFTP and SSH writes invoke conn_send from worker threads) short-circuit to pass-through. Scripts run on the foreground thread only.

Importing the API

Shared host bindings live in module syncterm. Every script imports the classes it needs:

import "syncterm" for Screen, Input, Conn, Hook, Key

An import does not grant all methods declared by that module. The host resolves known shared declarations so UI libraries can load in each VM. Calling a known capability owned by another VM aborts with "this capability is not available in this VM". Unknown foreign method declarations fail immediately during module loading, identifying the module, class, and signature. Constructing an unknown foreign class aborts with a missing-allocator error; the host never supplies an unrelated native payload. Namespace classes use ordinary Wren classes with foreign static methods. Menu-only data APIs are imported separately:

import "syncterm_menu" for Menu, DirectoryEntry, Settings, MenuFont, MenuError, BBSLoadDiagnostic, BBSListSource, MenuEncryption, MenuFontSlot

Cache is injected into the syncterm module from C as a module-level Directory object — there is no Wren-callable constructor. Import it like any other binding:

import "syncterm" for Cache

Hook Events

Hooks are registered as Wren callables (block, function, or method reference). Each call site walks its hook list in registration order; the first hook returning true consumes the event and stops dispatch. Returning false, returning a non-Bool, or throwing passes through to the next hook and ultimately to SyncTERM’s default handling.

Every registration returns a HookHandle (or null if the per-event limit is hit) — see HookHandle. Save it if the script needs to remove the hook later or read its metrics; toss it if not.

Hooks must run synchronously

Every hook fire is wrapped in a child fiber via Hook.dispatch_. For C1-contract hooks (see Two return contracts) the dispatcher needs the hook’s return value before it can decide what to do next; a hook that yields up to the dispatcher would strand it with no value to act on. C2-contract hooks ignore returns, but yielding still breaks the dispatch chain.

If a hook callback yields its own fiber directly (for example by awaiting an operation directly inside that callback), the dispatch wrapper detects the yield and logs:

hook handler must not yield directly; wrap parking work in
Fiber.new { ... }.call()

The hook is then treated as if it returned a non-Bool — the input passes through to the next hook and to SyncTERM’s default handling. A Fiber.abort from the hook is caught the same way: logged with a stack trace, treated as passthrough.

A hook that needs to wait on async results has two options that keep the hook itself synchronous. The first wraps the work in a child fiber and `.call()`s it from the hook body:

Hook.onKey { |k|
  if (k == Key.f2) {
    Fiber.new { runModalBrowser() }.call()
    return true
  }
  return false
}

.call() runs the child fiber synchronously until it yields (e.g. on an SFTP op or a Fiber.yield() waiting for a Wake.post). The child’s yield returns to the hook body — the immediate .call() caller — not up to the dispatcher. The hook still returns its Bool; the child resumes later via the framework’s result-queue drain.

The second option is to observe the operation with .then(fn), whose callback runs when the result arrives. The hook returns synchronously without ever yielding; the callback fiber is invoked later by the drainer:

Hook.onKey { |k|
  if (k == Key.f2) {
    SFTP.realpath(".").then(Fn.new {|r|
      // handle r …
    })
    return true
  }
  return false
}

Two return contracts

Every hook callback follows one of exactly two return-value contracts. Knowing which contract a hook uses tells you what (if anything) your return value does.

Contract Behaviour

C1 — replaceable

true consumes the event (no later hook sees it; SyncTERM’s default handling is bypassed). String replaces the event’s data where meaningful: raw bytes for onWire, semantic UTF-8 text for onInput. Any other return — false, null, a number, an instance, … — is a passthrough: the next hook in the chain sees the unmodified event, and SyncTERM’s default handling proceeds.

C2 — observe-only

The return value is ignored entirely. These hooks fire as a side-effect notification; the event continues regardless. A true or String return is dropped, AND the runtime logs a warning every time it happens — the noise is the diagnostic, intended to make the "I thought I could consume from here" mistake impossible to miss. Return null (or just don’t return) to silence it.

onKey, onPhysicalKey, and onMouse use C1 but have no meaningful interpretation for String returns (a key event, a PhysicalKeyEvent, or a MouseEvent isn’t a byte stream), so a String return from those is silently treated as passthrough. Use onWire for wire-byte replacement, or onInput for Unicode text replacement.

Method Argument Contract

Hook.onKey { |k| …​ }

k: complete KeyEvent, including Unicode text and modifiers

C1

Hook.onKey(key, fn)
Hook.onKey(key, modifiers, fn)

Filtered by logical key and modifier mask; the short form uses zero modifiers. Caps Lock and Num Lock are ignored. Other modifier bits must match exactly. The callback receives a complete KeyEvent; filtering happens before Wren entry.

C1

Hook.onInput { |b| …​ }

b: one decoded Unicode scalar, independent of wire encoding

C1. String replacements are NFC-normalized semantic UTF-8 text, capped at 256 bytes. Invalid UTF-8 or an oversized replacement logs an error and passes through the original scalar.

Hook.onInput(byte, fn)

Filtered: fn(b) only fires when b == byte (a Unicode scalar).

C1

Hook.onWire { |b| …​ }

b: one exact post-transport wire byte (0..255), before protocol classification or Unicode decoding

C1. A returned String contributes its exact bytes to the parser, without revisiting wire hooks. Replacements are capped at 256 bytes; an oversized replacement logs an error and passes through the original byte.

Hook.onWire(byte, fn)

Filtered: fn(b) fires only when the wire byte equals byte.

C1

Hook.onController { |ev| …​ }

Receives mapped controller value changes before graphics and CTerm. The Map has numeric "device" (local device ID), "type", "code" (evdev), and "value" (decoded button, axis, or hat value). Return true to consume. A neutral transition clears a previously delivered held value. Reporting to the BBS can be disabled while local scripts observe controllers. Registering the first controller hook starts polling for the focused session. Removing the last hook releases its request for polling.

C1

Hook.onPhysicalKey { |ev| …​ }

ev: PhysicalKeyEvent instance. Registering this hook enables ciolib physical-key event delivery for the session on builds/backends that support it.

C1

Hook.onPhysicalKey(evdev, fn)

Filtered: fn(ev) only fires when ev.evdev == evdev. C-side filter.

C1

Hook.onMatch(pattern, fn)

fn(m) fires when pattern matches the input stream. See "Streaming regex hooks" below.

C2. An "honor true-means-drop" semantics would require holding every input byte until every potential pattern resolves — not feasible for a streaming terminal. Use Hook.onInput for scalar-granular drops.

Hook.onMatchClean(pattern, fn)

Same as onMatch, with escape markers omitted from the text stream. CTerm owns sequence bodies, so colour codes, cursor moves, and DCS / OSC strings never split a literal pattern. A pattern like "Welcome" matches even when the BBS sends "We" + ESC[1;33m + "lcome".

C2

Hook.onMouse { |ev| …​ }

ev: MouseEvent instance

C1

Hook.onMouse(event, fn)

Filtered: fn(ev) only fires when ev.event == event. C-side filter.

C1

Hook.every(ms, fn)

ms: milliseconds; fn: callable

C2

Hook.onShellClose(fn)

Fires once when the SSH shell channel closes but the session is still alive (e.g. SFTP transfers may still be in flight). Typical use: pop a status / queue UI so the user can watch transfers finish, or signal a worker to wind down. See Session for owned lifetime leases that keep auxiliary work running after shell EOF.

C2

Hook.onDisconnect(fn)

Fires at the end of the disconnect path, after the main loop has fully exited but before the BBS / Wren VM tear down. SFTP is no longer available at this point (sftpc_finish has already run); use this for final local-state flushes (queue persistence, log close, etc.).

C2

Filtered variants share the same per-event registration array as the unfiltered forms, so dispatch order = registration order regardless of which form was used.

Hook.onWire fires on post-transport bytes before RIPscrip or CTerm classifies controls and text. It is the explicit byte-oriented hook for wire protocols; a returned String remains raw bytes. The default Hook.onInput and streaming match hooks are Unicode-facing: they see decoded text independent of whether the remote uses UTF-8 or a legacy codepage. Their replacements stay in the semantic text path rather than being re-encoded as if they had arrived from the remote. Sequence parameters and opaque protocol payloads bypass these Unicode hooks. onMatch retains control markers such as ESC; use onWire to inspect entire protocol sequences, and onMatchClean to match text across them.

Hooks run in registration order; the first one that returns Bool true (drop) or a String (replace) wins, and later hooks don’t see that unit. An onWire replacement is emitted before the next received byte, without recursively invoking the wire-hook chain.

Hook.every fires from the main-loop deadline check just before the sleep call. If the loop stalls long enough that more than one interval has elapsed, the deadline jumps forward to "now" rather than firing repeatedly to catch up.

The status bar is a separate dispatch path — see Status. A single render callable (rather than a hook chain) builds the row into a Surface the host hands it.

Streaming regex hooks

Hook.onMatch(pattern, fn) registers a regex against the decoded UTF-8 input stream. Each decoded byte is fed to a streaming Pike VM (Russ Cox’s NFA simulation, vendored under re1/); when a match completes, fn is called with a Wren List:

Hook.onMatch("login:") { |m|
  Conn.sendText("user\r")
  return false
}

Hook.onMatch("user (joe|jane|bob)") { |m|
  // m[0] = "user joe", m[1] = "joe"
  System.print("hi %(m[1])")
  return false
}

m[0] is the matched substring; m[1..] are the user-pattern’s capture groups in registration order. Both onMatch and onMatchClean are passthrough-only: the callback’s return value is ignored, and the matched text always reaches the terminal. Matching completes only after preceding bytes have passed through cterm, so these hooks cannot drop a complete matched span. Use the scalar-granular Hook.onInput hook when input must be dropped before reaching cterm.

Hook.onMatchClean(pattern, fn) omits ESC markers from CTerm’s decoded text stream. CTerm already withholds sequence bodies and opaque payloads from Unicode hooks. The matcher does not run a second escape parser, so an escape cannot leave it waiting for bytes which CTerm has already consumed. UTF-8 and legacy-codepage text use the same matching path, including sequences and Unicode characters split across receive buffers.

Grammar

RE1 implements a deliberately minimal regex dialect. These are all of the supported metacharacters:

Construct Meaning

literal byte

matches itself. Backslash has no special meaning — \ matches a literal backslash. To match an operator metacharacter literally, surround it via a non-capturing group with itself escaped is not possible; instead choose patterns that don’t conflict.

.

any byte (including NUL — the streaming VM does not treat NUL as end-of-input)

(…​)

capturing group

(?:…​)

non-capturing group

|

alternation

* + ?

greedy: zero-or-more, one-or-more, optional

*? +? ??

lazy (non-greedy) variants

Notably not supported (will be parsed as literal characters or syntax errors):

  • backslash escapes — \n, \t, \d, \w, \s, \xNN, …​

  • character classes — [abc], [a-z], [^…​]

  • anchors — ^, $, \b, \B

  • backreferences — \1, \2, …​

  • counted repetition — {n}, {n,m}

  • POSIX classes — , …​

  • inline flags — (?i), …​

Patterns are anchored at the current buffer start. "Match anywhere in the stream" is achieved by the dispatcher: when the VM returns IMPOSSIBLE (no thread can ever complete from the current buffer head), the oldest byte is dropped and the survivors are re-fed. In practice this means a pattern like "hello" matches the substring "hello" wherever it appears in the stream.

This trick requires that the pattern can produce IMPOSSIBLE — i.e., the first byte either advances the NFA or kills every thread. Patterns whose leading construct can match without consuming a byte keep threads alive on every input forever, the buffer fills, and matches start being silently dropped. Hook.onMatch therefore rejects patterns whose leading construct is *, +, or ? at registration time with Fiber.abort:

Allowed (1-byte anchor) Rejected (variable-width leading)

hello

.*hello

.bbs

.+bbs

(a|b)c

a*b

(?:foo|bar)baz

(a|b)*c

If you want a quantifier inside the pattern, anchor it with a fixed prefix: bbs (.) ` rather than `(.) bbs.

Match semantics

Pike VM has a leftmost-first-completing tie-breaking rule: as soon as any thread reaches a Match opcode, the match commits and remaining threads in the current step are discarded. In a streaming context this means open-ended quantifiers fire as soon as the shortest acceptable prefix is seen — a* matches the empty string at the first byte, a+ matches the first 'a' and stops.

For greedy-feeling behavior, terminate variable-length sub-patterns with a literal that follows them: user (.) ` (capture text up to a space) instead of bare `user (.). Newlines must be encoded as literal \n bytes in the Wren string (“\n” in the source code, which Wren resolves to a single 0x0A byte).

Limits

  • Buffer is capped at 4 KB per hook. When a partial match grows past the cap, the oldest half is dropped and the VM restarts — patterns that demand more than 4 KB of context will silently miss.

  • Up to 9 capture groups (RE1’s MAXSUB = 20 minus the whole-match pair).

  • Pattern compile errors (bad syntax, internal asserts) surface as Fiber.abort at the registration site, with the RE1 error text attached. The exception trace points at the offending Hook.onMatch call.

HookHandle

Every successful Hook.on* and Hook.every registration returns a HookHandle. The class has no Wren-callable constructor, so a script can’t fabricate one to remove arbitrary hooks — only its own.

import "syncterm" for Hook

var h = Hook.onKey { |k|
  if (k == 0x4200) {        // F8
    System.print("F8 pressed")
    return true
  }
  return false
}

// ...later...
h.remove()                  // no further dispatch
Member Meaning

remove()

Remove the hook from future dispatch. Safe to call from inside its own callback; in-flight dispatch finishes before resources are reclaimed. Returns true on first call, false thereafter. Removed registrations do not count against the live per-event limit.

callCount

Number of times the host has invoked this hook. Counts every wrenCall, regardless of whether the callback returned truthy or errored.

totalRuntime

Cumulative wall-clock seconds spent inside wrenCall for this hook, measured with the monotonic clock before and after each invocation.

minRuntime, maxRuntime

Smallest / largest single invocation time in seconds. Both read back as 0 for a never-fired hook; min is seeded on the first call.

HookHandle.remove() is safe from inside the hook’s own callback. The callable handle is released immediately and subsequent dispatches skip the removed entry. Outside dispatch, the host unlinks removed entries and frees their regex resources before registration, on the next pump, or when a host interpretation returns. The metrics remain alive until the script also drops the HookHandle and its foreign finalizer runs. Dropping a handle alone leaves an active hook registered. Metric getters on a removed handle keep working until the script drops the handle.

The conventional Input.next() / Input.next(ms) / Input.poll() primitives all return promptly; while a script is calling them in a loop the doterm() main loop is blocked, and inbound server bytes queue up in the socket buffer until the script returns.

For modal dialogs that should not block the main loop while the script idles between events, use Input.pushClaim(fn). The foreign installs fn as the current claim on a stack of input claims; whenever a key or mouse event arrives, the C-side dispatcher walks the stack head-first (newest first) and invokes the first claim whose owning fiber is still alive. The claim’s return value is a Bool — true consumes the event (no other claim or hook sees it), false passes it through to the next claim down and ultimately to the registered Hook.onKey / Hook.onMouse chain.

import "syncterm" for Input, Key, Wake, Screen, CTerm

var saved = Screen.save()
CTerm.suspended = true
var me = Fiber.current
var claim
claim = Input.pushClaim(Fn.new {|ev|
  // Decide consume / passthrough synchronously here — handlers
  // run from the C dispatch frame and must not yield.  Anything
  // we want to *do* with the event is dispatched by waking the
  // worker fiber via Wake.post; the worker yields/resumes on
  // its own schedule.
  Wake.post(me, ev)
  return true
})
while (true) {
  var ev = Fiber.yield()
  if (ev is KeyEvent && ev.matches(Key.escape, 0)) break
  Screen.window.print("got: %(ev)\n")
}
claim.pop()
Screen.restore(saved)
CTerm.suspended = false

The claim is a per-fiber slot: pushing twice from the same fiber replaces the existing claim in place (preserving stack position). Pushing from a different fiber adds a new entry on top, which becomes the foreground. Auto-prune at dispatch time drops claims whose owning fiber is isDone (so a script that aborts mid-claim doesn’t leave a dead handler installed). The returned ClaimHandle is the explicit way to remove the claim; pop() is idempotent.

CTerm.suspended is independent of the claim mechanism — any script can set it to claim the screen, and remote bytes pile up in the conn buffer behind it. When the TCP receive window fills, the remote sees its send() calls block or EAGAIN. Clearing the flag releases the backpressure and the buffered bytes drain through cterm normally.

The claim handler runs from the C dispatch frame via the same Hook.dispatch_ wrapper that protects regular hooks (see "Hooks must run synchronously" above) — so a yield inside the handler is caught and treated as not-consumed, and the input falls through to the next claim or hook chain. Heavy work belongs in a separate fiber that the handler wakes via Wake.post.

A hook callback can install its own claim and let it persist past the hook return — perfect for "F2 opens a modal that captures input until Esc":

Hook.onKey(Key.f2) { |k|
  var worker
  worker = Fiber.new {
    var claim = Input.pushClaim(Fn.new {|ev|
      Wake.post(worker, ev)
      return true
    })
    while (true) {
      var ev = Fiber.yield()
      if (ev is KeyEvent && ev.matches(Key.escape, 0)) break
      // ...
    }
    claim.pop()
  }
  worker.call()
  return true
}

For more elaborate UIs, the App class (see App) wraps this pattern and provides synchronous claim decisions based on its own state (modal stack, focused widget, mouse hit-test) plus a runChild helper that lets handler code yield safely on async work without breaking the App’s event loop.

Built-in REPL

The immediate-mode REPL belongs to the VM which owns the current screen. In graphical and native-console backends, Ctrl+` opens it from the main menu or a connected session. In ANSI and ncurses modes, Ctrl+Q opens it from the main menu; while connected, press Ctrl+S and select Wren Console from the Online Menu. The shared UI is implemented in scripts/wren_console.wren and can be overridden with ~/.local/share/syncterm/scripts/wren_console.wren. The connected entry point is scripts/auto/connected/console.wren; the persistent menu binds its backend-appropriate key in scripts/auto/menu/main_menu.wren.

While the connected console is open the doterm() main loop is suspended. Connection bytes accumulate in the socket buffer but aren’t drained until you exit the console. This is acceptable for a development tool; not appropriate for "watch a slow BBS scroll" use cases. The menu already uses a synchronous event loop, so opening its console does not change its event-pumping model. When the menu was entered through Alt+E, the connection is already parked for the entire menu visit.

When physical-key reporting is active, the console drains and ignores PhysicalKeyEvent press/release edges; editing commands use the corresponding translated KeyEvent. This keeps host key state synchronized without sending console keystrokes to the connected application.

The editor stores cursor positions as UTF-8 byte offsets for Wren string slicing, but Left, Right, Backspace, Delete, and Ctrl+W move only across complete Unicode codepoints. The displayed cursor column follows the glyph width selected by Screen.textWidth() and eight-column tab stops. Editing is codepoint-based: grapheme-cluster navigation and Unicode word-breaking are not performed. Display boundaries normalize text to NFC and measure complete extended grapheme clusters.

The REPL evaluates input through REPL.eval(module, src). The input is pre-classified by inspecting its leading non-whitespace token: source that begins with a Wren statement keyword (var, class, import, return, break, continue, if, while, for) is compiled as a statement; everything else is compiled as an expression. Successful expressions print their result quoted with C-style escapes (so "7" the string and 7 the number are visibly distinct); statements print nothing.

Variables and class declarations persist across submissions inside the active module:

> var x = 1 + 2
> x * 10
30
> class Foo { static greet { "hi" } }
> Foo.greet
"hi"

REPL Commands

Command Action

/help, /?

Print commands, editing keys, history navigation, scrollback navigation, and exit keys.

/in <module>

Switch the eval target to <module>. Default is syncterm in the connected VM and main_menu in the menu VM. Use this to inspect or mutate any other loaded module. /in with no argument prints the current target.

/mods

List every Wren module currently loaded into the VM, alphabetically sorted. Includes core (Wren’s built-in classes), every embedded module (syncterm, wren_console, connected or main_menu), every user script loaded from the scripts directory, and any module pulled in via import.

/quit, /q

Close the REPL and return to the connected session or main menu.

Modules can plug in their own /<command> entries via WrenConsole.register(name, help, fn):

import "wren_console" for WrenConsole

WrenConsole.register("greet", "say hello [<name>]") { |args|
  if (args == "") {
    System.print("hello!")
  } else {
    System.print("hello, %(args)!")
  }
}

The handler is called with the raw argument string — everything after the command name and its first separating space, or "" if none. Re-registering an existing name overwrites the previous binding. Names can’t contain spaces (the dispatcher splits on the first one). The dispatch wraps the handler in Fiber.new {}.try() so a runtime abort surfaces as a logged error instead of tearing the console out from under itself. /? lists every registered command with its help text alongside the built-ins.

WrenConsole.unregister(name) drops a registration (idempotent — no-op if not registered); WrenConsole.commands returns the sorted list of currently-registered names for tooling.

REPL Key Bindings

Key Action

Left / Right

Move the cursor within the current input line.

Home / End

Jump to start / end of the current input line.

Backspace

Delete the character before the cursor.

Delete

Delete the character at the cursor.

Up / Down (live mode)

Walk command history. If the line currently has typed text, that text becomes a prefix anchor — only history entries starting with it are visited.

PgUp / PgDn

Page through the scrollback log buffer. PgUp from live mode pins the current top of view; PgDn returns to live once you’ve scrolled past the tail.

Up / Down (scrollback mode)

Single-row scroll. Down past the tail rejoins live mode.

Enter (blank or whitespace-only)

Advance to a fresh prompt row without evaluating.

Ctrl+W

Backward kill-word, ending at the cursor (the tail past the cursor is preserved).

Ctrl+L

Clear the screen and the in-memory log. Returns to live mode.

Middle-click

Paste from the system clipboard at the cursor. Valid Unicode text and Tab are inserted. CR, LF, and CRLF each delimit one submitted line. Other C0, DEL, and C1 controls, malformed UTF-8, and non-scalar encodings are discarded without discarding valid text around them.

Alt+drag

Hand off to the existing select-and-copy gesture.

Ctrl+` (graphical/native-console) / Ctrl+Q or Ctrl+S (ANSI/ncurses)

Close the REPL and return to the owning screen.

Esc / /quit

Close the REPL in every backend.

Object Model

The remainder of this document is a reference for every foreign class exposed in the syncterm module.

A note on toString: every class with an explicit toString method returns it strictly for human-readable debug output — the format that System.print(value) and string interpolation "%(value)" emit when no other rendering is appropriate. The exact string is not part of the API contract; it may change between SyncTERM versions to add or remove fields, reformat, etc. Scripts that need specific data should call the named property accessors (cell.ch, event.key, surface.width) — never parse toString output. Without an explicit toString a foreign would print as something like [instance of Cell], which is uniformly less useful than even a minimal Cell(0x41 attr=0x07); that’s the only motivation for having these methods at all.

Error / ScriptError

Error is the polymorphic base for every recoverable-failure value type the API hands back: SFTPError, FileError, WONError, ConnError, TransferError, CTermError, ScreenError, FontError, menu-only MenuError, plus any user-defined ScriptError subclass. Lets a script catch any of them with one check:

import "syncterm" for Error

var v = something_that_might_fail()
if (v is Error) {
  System.print("failed: %(v)")        // toString includes the type
  return
}
// proceed with the typed result

Every concrete Error subclass guarantees the contract:

Member Description

code

Numeric error code from the type’s enum (e.g. IOErr., WONErr.); MenuError.code is null when its C operation supplies no portable reason.

message

Human-readable diagnostic, may be null.

toString

Format with the subclass name as prefix.

Type-specific extras (FileError.errno, WONError.offset, ConnError.partial, FontError.nativeCode, MenuError.nativeCode, SFTPError.serverStatus, SFTPError.isTransient) live on the subclass.

Error itself is empty by design: foreign subclasses (FileError etc.) need the parent to be field-free or Wren rejects the inheritance at module-load time (the numFields == -1 && superclass→numFields > 0 check at wren_vm.c:559-563).

ScriptError

Concrete Wren-side base for script-defined error types. Use this when a script wants to surface its own typed error without writing C bindings:

import "syncterm" for ScriptError

class ConfigError is ScriptError {}

if (something_bad) {
  return ConfigError.new(42, "missing required field 'host'")
}

ScriptError provides the same code / message / toString getters every foreign Error subclass exposes, so callers see uniform behaviour from is Error and the field accesses regardless of whether the value came from C or Wren. The default toString uses the runtime class name ("ConfigError(42): missing required field 'host'"); subclasses may override for a different format.

Member Description

ScriptError.new(code, message)

Construct. code is a Num, message a String (or null).

code

The integer passed to the constructor.

message

The string passed to the constructor.

toString

"<className>(<code>): <message>".

Screen

Drawing/state queries return their documented successful value or a ScreenError. Drawing/state actions return null on success or ScreenError; test for Error before using a returned value. These operations are available in the menu, picker and connected VMs, each using its own console.

Read/write access to the terminal display surface. Screen itself exposes whole-screen and absolute-coordinate operations; per-window operations live under Screen.window.

Member Description

Screen.size

[width, height] of the entire screen.

Screen.save()

Save the entire screen contents. Returns a host-created ScreenSnapshot. The snapshot owns its saved cells, palette and pixel planes; garbage collection releases those resources. Keep the value reachable while it is needed. ScreenSnapshot has no public constructor, and the same snapshot may be restored more than once.

Screen.restore(handle)

Restore a previously saved ScreenSnapshot.

Screen.modalRun(fn)

Run fn with the screen and the wire-byte pump under our own control: snapshot the screen + suspend CTerm before the call, unsuspend + restore the screen after. The previous CTerm.suspended value is saved and restored, so nested modalRun calls compose. Returns the callback’s result. Callback errors restore the snapshot and the previous suspension state before propagating the same error object. The callback runs in a scoped child fiber; cooperative yields and Operation awaits keep the cleanup boundary intact. During VM shutdown only retained cleanup functions run, in reverse entry order; parked callback bodies and their waiters are not resumed. Cleanup failure does not replace an earlier callback error. + [source,wren] ---- Screen.modalRun(Fn.new { var app = App.new() // …​ configure app …​ app.runSync() }) ---- + Without this, every modal-screen script duplicates the same four-line dance (Screen.save, CTerm.suspended = true, work, unsuspend + restore) — and forgetting the suspended toggle leaks remote bytes onto the modal screen the next time the BBS sends something.

Screen.readRect(sx, sy, ex, ey)

Read a rectangle of cells (1-based, inclusive). Returns a Surface sized (ex-sx+1) × (ey-sy+1), or ScreenError on invalid integral coordinates, capture failure, or backing-storage OOM. Arguments of the wrong type, fractional values, NaN, and infinity are programmer errors and abort the calling fiber.

Screen.putRect(src, dstX, dstY), Screen.putRect(src, srcRect, dstX, dstY)

Blit a Surface to the screen at (dstX, dstY) (1-based). The 4-arg form takes a Rect sub-rect of src; the 3-arg form blits the whole source. Out-of-screen regions are clipped silently.

Screen.update(fn)

Compose synchronous cell, pixel, and cursor updates in one presentation batch. Returns the callback result; nesting is supported, yielding is not. See Pixel screen operations for error and cleanup behavior.

Screen.pixelSize

Internal raster size as [width, height], or ScreenError; an unsupported pixel surface has code IOErr.notSupported.

Screen.cellPixelSize

Character-cell size as [width, height] pixels, or ScreenError when it is unavailable.

Screen.readPixels(x, y, width, height), Screen.readPixels(x, y, width, height, force)

Capture a 0-based raster rectangle as a PixelBuffer. See Pixel screen operations for force and failure behavior.

Screen.setPixel(x, y, color)

Set one 0-based raster pixel to a native pixel color.

Screen.blitPixels(buffer, descriptor), Screen.blitPixels(buffer, mask, descriptor)

Draw a PixelBuffer using a PixelBlit, optionally through a PixelMask.

Screen.attr, Screen.setAttr(a)

Read or set the active text attribute byte.

Screen.hyperlinkId, Screen.setHyperlinkId(id)

Hyperlink ID attached to subsequent window writes. 0 clears. Allocate IDs through Hyperlinks.add.

Screen.supports, Screen.font, Screen.palette, Screen.cursor, Screen.videoFlags, Screen.color, and Screen.window are getters that return the helper class so the script can call its static members.

ScreenError

Immutable ScreenError is Error values expose code, message and toString, with no public constructor or setters. code preserves the actual portable native result, including unrecognized integers. Existing binding-owned rejected regions, unavailable pixel capabilities and capture-storage allocation failures use IOErr.outOfRange, IOErr.notSupported and IOErr.outOfMemory respectively; these are binding diagnoses rather than fabricated native results. The owned message identifies the failed operation/check. Errors hold no console, session, input or borrowed native resources and remain valid across later calls and GC.

Native operations may change logical state before presentation fails. A returned error therefore does not imply rollback or permit automatic replay. Success reports native acceptance, not completion of a later asynchronous presentation. Restoring a screen snapshot synchronizes its saved Wren font slots whenever native state was applied, including a later presentation failure. Rejected restores leave them unchanged. Snapshots retain their existing owner, geometry and lifetime limits.

Screen.update, Screen.modalRun, CustomCursor.preserve and VideoFlags.preserve return acquisition/cleanup ScreenError values. Failed acquisition does not run the callback. Required cleanup is attempted after entry; a callback’s returned Error takes precedence over cleanup failure, and callback aborts propagate unchanged. Otherwise cleanup failure replaces the normal callback result. Update callbacks still cannot yield; modal/preserve callbacks retain their existing cooperative-yield, Operation and shutdown cleanup behavior. Finalizers remain native cleanup boundaries and cannot return errors to an absent caller.

Live setters were replaced with explicit methods without aliases. Local staged cursor/flag setters and local offscreen-object APIs are unchanged. The bundled UI checks drawing results, propagates unhandled errors through its existing fiber handling and attempts independent restoration. Unsupported decorative title and pointer operations are skipped; URL-open failure still falls back to copying, with success announced only after copying succeeds. No clipboard protocol or VM authority changed.

Screen.supports

Read-only capability flags (Bool or ScreenError) reflecting what the current display backend (SDL, X11, Win32, etc.) can do. Unsupported capabilities return false; failure to acquire the native capability state returns ScreenError. Scripts that adapt their output to the backend should branch on these.

Flag True when the backend can…

loadableFonts

Replace the bitmap font in any slot at runtime.

altBlinkFont

Select a registered alternate font with the source blink bit.

altBoldFont

Select a registered alternate font with the source bright bit.

brightBackground

Render at least sixteen indexed colours, so the source blink bit can also select a bright background.

paletteChange

Mutate the active palette at runtime.

pixels

Address individual pixels (pixel-aware backends only — needed for RIP, SIXEL, SkyPix).

customCursor

Render a non-default cursor shape.

fontSelection

Switch fonts via the SyncTERM font-selection UI.

windowTitle

Set the OS window title.

clipboard

Advertise native clipboard text read/write support.

openUrl

Advertise native URL-opening support.

windowName

Set the OS window’s class / icon name (X11).

windowIcon

Set the OS window’s icon image.

extendedPalette

Address palette indices beyond 16.

blockyScaling

Use nearest-neighbour scaling for the pixel-doubled display.

externalScaling

Defer scaling to the OS / window manager.

closeLock

Inhibit the OS window close button while a BBS session is active.

The clipboard and URL flags mirror the native capability bits for the current VM’s console, including in menu, picker and connected VMs. They describe advertised backend support, not permission to use an operation or a guarantee that it will succeed. Reading them does not access the clipboard or open a URL.

Screen.window

Operations scoped to the active text window. Cursor position, character output, line edits, and clearing all act inside the window’s rectangle. Coordinates are window-relative (1, 1 is the top-left of the window, not the screen). Invalid bounds, out-of-window positions and invalid character values remain programmer errors. Native console failures return ScreenError; an error can follow partial drawing or a committed state change and does not promise rollback.

Member Description

Screen.window.bounds, setBounds(box)

[sx, sy, ex, ey] of the active window (screen-absolute, 1-based, inclusive). Setting bounds preserves the screen position if it is inside the new window and otherwise moves it to the window origin.

Screen.window.position, setPosition(coord)

[x, y] cursor position, window-relative.

Screen.window.putChar(c)

Write one character at the cursor.

Screen.window.print(s)

Write a string at the cursor.

Screen.window.clear()

Clear the window with the current attribute.

Screen.window.clearToLineEnd()

Clear from cursor to end of line.

Screen.window.deleteLine(), insertLine(), scroll()

Line editing inside the window.

Screen.font

Per-slot font management. Five slots (0..4) match SyncTERM’s font slot model.

Screen.font[i] reads the font index in slot i. Screen.font[i] = n selects font n for slot i; assigning slot 0 also resets the normal slot 1, matching the legacy default-font operation. Slots 1 through 4 are respectively normal, source-bright, source-blink, and source-bright plus source-blink. VideoFlags.altChars and blinkAltChars enable the two selectors. Selection happens when text is written, and the resolved internal font identifier is retained in the cell. Clear, line insertion/deletion, and scroll operations likewise resolve the font for the blank cells they create. Later flag or slot changes do not reinterpret existing cells, and Screen.putRect preserves the already-resolved fonts in its Surface. Use the Font class (see Font) for the named built-in indices.

Screen.palette

24-bit-RGB palette as 0xRRGGBB integers.

Screen.palette[i] reads an RGB value or returns ScreenError. Screen.palette.set(i, c) writes an entry and returns null or ScreenError. Both retain the existing script index range, 0 through 255.

The first 16 entries are the legacy-attribute palette. Read each entry through the indexed API and write it through set.

Note
term.c, cterm.c, and ripper.c all do their own palette manipulations. Concurrent edits from a script and from the terminal code may not compose cleanly.

Screen.cursor — CustomCursor

Cursor geometry: scanline range, blink rate, visibility.

The class supports two usage modes:

  • Static (live state): static getters read the cursor and explicit static methods update it immediately. Screen.cursor.setBlink(false) hides the blink on the next refresh. Each live setter method under the hood does a full read-modify-write of the renderer’s cell cursor state — so a single static write IS atomic for that one field, but a chain of static writes is NOT atomic across fields. The renderer can paint between them, briefly showing intermediate states. For multi-field changes, use the instance path.

  • Instance (staged edit): CustomCursor.new() (or CustomCursor.current) snapshots the current values. Modify the instance’s properties locally, then apply() to commit as one locked state change regardless of how many fields changed.

CustomCursor.preserve(fn) is a convenience for the common "snapshot, change, restore" pattern: snapshots the live cursor, runs fn in a scoped child fiber, then re-applies the snapshot. It returns fn’s result and restores state before propagating a callback error. Nested calls, cooperative yields, Operation awaits, and VM shutdown have the same cleanup semantics as `Screen.modalRun.

Static getters and instance properties: startLine, endLine, range, blink, visible. Live writes use setStartLine(n), setEndLine(n), setRange(n), setBlink(b) and setVisible(b), returning null or ScreenError. Instance setters edit only the local snapshot; apply() returns null or ScreenError. new(), current and the preset getters return a snapshot or ScreenError, with no fabricated defaults after a failed read.

Pre-defined snapshots:

Snapshot Equivalent legacy code

CustomCursor.normal

Mode-default cursor shape (legacy code 2).

CustomCursor.solid

Solid block cursor (legacy code 1).

CustomCursor.none

Hidden cursor (legacy code 0).

A CustomCursor.current snapshot also retains a terminal-owned pixel cursor opaquely, so applying an unchanged snapshot or using CustomCursor.preserve restores it. Editing a cursor field or applying a preset selects the ordinary cell cursor. SkyPix’s native cursor position/colour/timer is owned by the terminal; it is not a bitmap drawing operation and is excluded from pixel captures and scrollback rasters.

Screen.videoFlags — VideoFlags

Boolean video-output flags, with the same static-vs-instance pattern as CustomCursor — including the chained-static-writes non-atomicity caveat and the VideoFlags.preserve(fn) snapshot helper. Static reads return Bool or ScreenError; static writes use setAltChars(b), setNoBright(b), setBgBright(b), setBlinkAltChars(b), setNoBlink(b) and setLineGraphicsExpand(b), returning null or ScreenError. new() and current return a snapshot or ScreenError; instance setters remain local and apply() returns null or ScreenError. expand remains read-only.

Property Meaning

altChars

Let source attribute bit 3 select font slot 2 instead of slot 1 (and slot 4 instead of slot 3 when bit 7 also selects a font).

noBright

Prevent source attribute bit 3 from selecting a bright foreground palette entry. This does not change the independent bold style flag or the source bit’s use as an alternate-font selector.

bgBright

Treat the high-intensity bit on the background nibble as a bright background. Its blink and alternate-font meanings remain independently controlled.

blinkAltChars

Let source attribute bit 7 select font slot 3 instead of slot 1 (or slot 4 when bit 3 also selects a font).

noBlink

Prevent source attribute bit 7 from blinking. The same bit may still select a bright background or alternate font.

expand

Read-only. True when the backend is using a cell one pixel wider than its font. The extra column is blank unless lineGraphicsExpand applies. It is fixed by the video-mode geometry and cannot be changed on a live console.

lineGraphicsExpand

Apply the right-edge duplication to box- drawing glyph indices in the 0xC0..0xDF range when expand is true (the VGA ninth-column rule).

Screen.color — Color

Build and inspect 24-bit RGB values. Returned values are raw 0xRRGGBB without the high RGB-mode bit; the bit is added when writing into a Cell field via fgRgb= / bgRgb=.

Method Description

Color.fromRgb(r, g, b)

Pack three 8-bit components into a uint32.

Color.fromAttr(attr)

Decode an attribute byte into [fg, bg] 24-bit RGB through the active sixteen-colour palette and current bright/background video-flag policy. Returns ScreenError if native colour state cannot be read.

Color.toLegacyAttr(fg, bg)

Map 24-bit RGB foreground and background colours to the nearest legacy text attribute byte in that same active palette. Matching uses YCoCg distance; bright foreground or background candidates are included only when the current video flags give those attribute bits a colour meaning. Returns ScreenError if native colour state cannot be read.

Pixel graphics

The pixel API exposes ciolib’s internal raster directly in the connected, menu, and picker VMs. Raster coordinates are 0-based and refer to the unscaled video-mode surface, not operating-system window coordinates. User display scaling does not change these coordinates. Screen.pixelSize includes any raster rows that do not belong to a complete text cell.

Pixel buffers, masks, and blit descriptors are foreign objects owned by the VM that created them. Their native allocations are released by Wren’s garbage collector. They cannot be passed between SyncTERM’s isolated VMs.

PixelColor

Pixel buffers retain ciolib’s native colour words. A native word is either a palette index in 0..65535 or a 24-bit RGB value tagged with CIOLIB_COLOR_RGB. A plain 0xRRGGBB number is therefore not necessarily a native RGB colour; construct it with PixelColor.rgb before placing it in a buffer.

Member Description

PixelColor.rgb(rgb)

Tag a raw 0xRRGGBB value as native RGB.

PixelColor.palette(index)

Construct a native palette colour. index may be 0..65535.

PixelColor.isRgb(value)

Return true when value is a tagged RGB colour.

PixelColor.rgbValue(value)

Return raw 0xRRGGBB for a tagged RGB colour, or null for a palette colour.

PixelColor.paletteIndex(value)

Return the index for a palette colour, or null for tagged RGB.

PixelColor.toRgb(value)

Return raw 0xRRGGBB, resolving palette colours through the active palette. Returns null if the palette index cannot be resolved.

All methods reject fractional, negative, out-of-range, or malformed native colour values by aborting the calling fiber.

PixelBuffer

PixelBuffer is a row-major Sequence of native colour words. Linear index i is (y * width) + x. Ordinary reads, writes, fills, and blits operate on the native array directly.

Member Description

PixelBuffer.new(width, height), PixelBuffer.new(width, height, fill)

Allocate a buffer, initially palette index 0 or fill.

width, height, count

Dimensions and total pixel count.

[i], [i]=(color)

Read or write one row-major native colour word.

pixelAt(x, y), setPixel(x, y, color)

Read or write one 0-based buffer coordinate.

fill(color)

Fill the primary plane.

clone()

Copy the buffer and both blink-phase planes. Returns null on allocation failure.

blit(source, descriptor), blit(source, mask, descriptor)

Composite another PixelBuffer into this buffer, using PixelBlit and an optional PixelMask. Returns null on success or PixelError. Available in all three VMs independently of Screen.supports.pixels.

PixelBuffer.fromRgb24(width, height, bytes), PixelBuffer.fromRgb24(width, height, bytes, alternateBytes)

Import packed RGB bytes in R,G,B order. Each string must contain exactly width * height * 3 bytes. Imported pixels become tagged RGB colours.

rgb24

Export the primary plane as packed RGB bytes. Palette words are resolved through the active palette.

hasAlternate, alternateAt(i)

Inspect the optional alternate blink-phase plane. alternateAt returns null while no explicit plane exists.

fastBlinkAt(i), setFastBlink(x, y, fast)

Read or set a pixel’s Boolean blink rate. False selects slow blink. The first true bit allocates a packed rate mask and, if needed, an alternate plane initialized from the primary colours. Clearing the alternate plane releases the mask. Edits to individual colours preserve the pixel’s chosen rate.

setAlternate(x, y, color), fillAlternate(color), setAlternateRgb24(bytes)

Create or update the alternate plane. Its first creation copies the complete primary plane before applying the requested change.

alternateRgb24

Export the alternate plane as packed RGB, or return null when it is absent.

clearAlternate()

Remove the explicit alternate plane. Native drawing then uses the primary plane for both blink phases.

PixelBuffer.fromPpm(source)

Decode the first P3 or P6 PPM image. Values use PPM’s BT.709 transfer function and are converted to 8-bit sRGB; maximum values through 65535 are accepted.

PixelBuffer.fromJxl(source)

Decode JPEG XL. Returns null for invalid data, allocation failure, or an unavailable decoder. The first displayed frame is colour-managed to 8-bit sRGB; alpha is discarded.

PixelBuffer.jxlSupported

true when libjxl was compiled in and can be loaded. The JXL methods are present even when this is false.

Decoder source may be a binary Wren String or a readable, consent-bounded File. A File is mapped and decoded directly; SyncTERM does not first copy its contents into a Wren string. Decoded images contain only a primary plane.

Capture and clone preserve the primary and alternate colours and the packed blink-rate mask. RGB24 export is a conversion and resolves palette references at export time; use native indexing when palette identity must survive a round trip.

Buffer blits use the existing descriptor’s source rectangle, signed destination origin, mask origin, flips and independent integer scaling. Zero source extents mean the remainder, resolved on each call without changing the descriptor. The destination is clipped; masks control transparency and there is no alpha blending. Native palette words and tagged RGB values are copied without palette resolution. Source, mask and descriptor remain unchanged, except that a self-blit also changes its source because source and destination are the same object.

The two colour planes and the optional blink-rate bits are preserved. A source alternate plane causes the destination to acquire one, initially copying its whole primary plane; unpainted pixels keep those values. Without a source alternate plane, primary pixels supply both destination phases. Native plane creation happens before clipping/mask drawing, so a blit that paints no pixels can still create a plane or fail its allocation. Overlapping self-blits snapshot the source colours and rate bits before drawing. Distinct-buffer blits allocate missing alternate or rate storage as needed. No screen, file or network operation is performed, and no arguments are retained after the synchronous call.

Wrong argument types abort the calling fiber. The masked overload requires a PixelMask; use the two-argument overload rather than null for an unmasked blit. Invalid source/mask regions, including empty source regions, return PixelError with IOErr.outOfRange. An empty destination returns the native IOErr.invalidArgument. Native allocation/validation failures preserve their actual code. Returned errors leave destination pixels and plane ownership unchanged.

PixelError

Immutable PixelError is Error values expose code, message and toString, with no public constructor or setters. code retains the actual native integer status, including unrecognized values; binding-rejected source/mask regions use IOErr.outOfRange. The owned message identifies the operation and reason. Errors retain no buffer, mask, descriptor or console resources and survive later calls and garbage collection independently. This result type applies to PixelBuffer.blit; other existing pixel operations retain their documented result contracts.

PixelMask

PixelMask is a row-major Sequence of Bool values. A true bit draws its source pixel; a false bit leaves the destination unchanged.

Member Description

PixelMask.new(width, height), PixelMask.new(width, height, fill)

Allocate a false-filled mask, or initialize every bit to fill.

PixelMask.fromBits(width, height, bits)

Import continuous row-major packed bits, most-significant bit first. The string length must be ceil(width * height / 8).

PixelMask.fromPbm(source)

Decode a P1 or P4 PBM from a binary String or readable File. P4’s per-row padding is removed; PixelMask.bits always uses continuous bits.

width, height, count, [i], [i]=(value)

Dimensions and linear Boolean access.

bitAt(x, y), setBit(x, y, value), fill(value)

0-based coordinate access and bulk fill.

bits

Export continuous row-major packed bits, most-significant bit first.

PixelBlit

PixelBlit is a reusable mutable descriptor. PixelBlit.new() selects the whole source, destination (0, 0), scale (1, 1), mask origin (0, 0), and no mirroring.

Member Description

sourceX, sourceY

0-based source origin. Values must be non-negative integers.

sourceWidth, sourceHeight

Source extent. Zero means the remainder of that source dimension, evaluated when the descriptor is used.

destinationX, destinationY

Signed 0-based destination origin. Negative values request clipping at the left or top edge.

scaleX, scaleY

Positive integer nearest-neighbour scale factors.

maskX, maskY

0-based mask origin. The mask region has the same unscaled extent as the source region.

flipX, flipY

Mirror the selected source and corresponding mask region before scaling.

Descriptor setters reject wrong types, fractional values, out-of-range coordinates, and zero scale by aborting the calling fiber. Reusing a descriptor does not retain a source, mask, or destination reference.

Pixel screen operations

Screen.update(fn) composes synchronous cell, pixel, and cursor changes as one presentation batch. The callback runs immediately, may nest another Screen.update, and returns its result. Ordinary presentation, including blink and expose repaint events, waits until the outermost update ends. The batch closes before a callback error is propagated; yielding from the callback is rejected and also closes it. This groups drawing; it does not roll back changes on error. Do not wait for input, open a modal, switch screen modes, or run an event loop inside the callback. Native code that explicitly forces a presentation can still bypass batching.

Use this when text cells provide a graphical UI’s metadata and base glyphs, with pixel operations completing its appearance. Screen.readPixels can inspect the composed raster inside the batch without presenting it.

Screen.readPixels(x, y, width, height) captures a positive-sized rectangle and returns a new PixelBuffer. Passing force=true first requests a full refresh from text vmem before capture; use the default false when capturing pixel changes that have already been drawn. Capture returns ScreenError for an unsupported backend (IOErr.notSupported), an out-of-screen rectangle (IOErr.outOfRange), or allocation failure (IOErr.outOfMemory).

Screen.setPixel(x, y, color) and both Screen.blitPixels overloads return null on success or ScreenError. A blit validates the source and optional mask regions, clips the scaled destination to the screen, and returns null without drawing when the entire destination is off-screen. Scaling is nearest-neighbour and independent in X and Y. If the source has no alternate plane, its primary pixels are used for both destination blink phases. Masks are the transparency mechanism; there is no alpha blending.

Blitting uses the supplied native buffers directly and provisions missing rate storage as needed. Keep decoded or constructed buffers and descriptors for repeated sprite draws rather than rebuilding RGB strings. Capture, decode, clone, RGB24 conversion, and first alternate-plane creation do allocate.

var sprite = PixelBuffer.fromPpm(ppmBytes)
var mask = PixelMask.fromPbm(pbmBytes)
var blit = PixelBlit.new()
blit.destinationX = 40
blit.destinationY = 24
blit.scaleX = 2
blit.scaleY = 2
blit.flipX = true

if (sprite != null && Screen.supports.pixels) {
  Screen.blitPixels(sprite, mask, blit)
}

Invalid argument types, fractional or out-of-range integers, invalid native colours, malformed packed lengths, and invalid descriptor fields abort the calling fiber. Constructors also abort on allocation failure because Wren foreign constructors cannot return null; offscreen factories, decoders and clone return null for recoverable allocation or decoding failure. Screen capture returns ScreenError. The alternate-plane mutators leave the buffer unchanged and abort the calling fiber if the plane’s first allocation fails.

Input

Unified blocking and nonblocking reader for keyboard and mouse events.

Member Description

Input.next()

Block until the next event; return KeyEvent, PhysicalKeyEvent, or MouseEvent. Physical press/release edges are returned one per call; when the backend’s coalesced physical-key wake represents multiple queued edges, Input.next re-arms the wake until the queue is drained.

Input.next(ms)

Wait up to ms milliseconds; return the event or null on timeout. Filtering unrelated host events does not restart the deadline.

Input.poll()

Return immediately with the next pending event, or null if nothing is pending.

Input.unget(ev)

Push an exact copy of a KeyEvent, PhysicalKeyEvent, or MouseEvent back to the front of this VM’s input queue. Other values abort the calling fiber.

Input.synthesizePhysicalKey(evdev, pressed)

Synthesize a physical key edge. evdev is an evdev key code number; pressed is true for press and false for release. Duplicate edges are suppressed by the console’s held-key tracking. Synthesized events have zero modifiers and repeat=false.

Input.mousedrag(), Input.mousedrag(forceRect)

Hand off to SyncTERM’s full-screen drag-select gesture. This uses the current screen dimensions and does not depend on a connected terminal. In a live RIP3 connection, selection uses the selected text window’s grid, font and pixel origin. Suspended terminal UI continues to use its own screen. The default is line selection; forceRect=true makes rectangular selection the default for Wren UI chrome. Holding Alt when pressing button one inverts that default for the drag, so Alt+Drag selects a block in line mode or lines in rectangular mode. Changing Alt after the press has no effect. Selected concealed characters become visible during the drag and are included in the clipboard text. Selection temporarily redraws text over pixel graphics. The complete screen, including both pixel planes, is restored when the drag finishes or is interrupted by another input event.

Input.setMouseVisible(b)

Show or hide the mouse cursor; return null or ScreenError. There is no ciolib query for visibility, and tracking it from Wren would drift if other code shows or hides the cursor.

Input.mouseEvents, Input.mouseEvents=(mask)

Read or set the bitmask of Mouse. events the terminal will deliver. Event IDs are limited to 0 through 49, so every valid mask is exactly representable by Wren Num. UI code typically saves the current mask, *replaces it with exactly the events it cares about, and restores on exit so the surrounding terminal’s mouse mode survives.

Input.enableMouseEvent(ev), Input.disableMouseEvent(ev)

Single-event toggles for the same mask.

Input.pushClaim(fn)

Push fn onto the input claim stack as the current claim for the calling fiber. fn(ev) is invoked by the C-side dispatcher with the next key, physical-key, or mouse event and must return Bool — true consumes, false passes through to the next claim down (and ultimately to registered Hook.onKey / Hook.onPhysicalKey / Hook.onMouse). Per-fiber slot: a same-fiber re-push replaces the existing claim in place; a different-fiber push adds a new entry on top. Returns a ClaimHandle. See Modal Input.

Once a process-close request has been read, Input.next(), Input.next(ms), and Input.poll() continue returning Key.quit until SyncTERM exits. UI code should use App, which reserves the event for call-stack unwinding and supports the explicit Widget.atExit exception.

For posting a synthetic resume to a parked fiber (the wake mechanism that Hook.onInput-style callbacks use to nudge a UI fiber), see Wake.

Claims and wakes are stored independently for each VM. The persistent menu and picker currently use the synchronous Input.next path; the connected-session owner loop is responsible for invoking claim dispatch and draining wakes. Registering a claim alone does not create a background pump.

KeyEvent

Carries committed Unicode text, a logical named key, a numeric keypad byte, or a DoorWay scan. These meanings remain distinct. Display font selection never determines input text; connection encoding is applied only when an event is forwarded through CTerm.sendKey.

Member Description

KeyEvent.new(key)
KeyEvent.new(key, modifiers)

Construct a named Key event or Unicode scalar event. The short form uses zero modifiers. Surrogates, fractions, and values outside the key namespace are rejected. A scalar constructs committed text; use a named key for keyboard controls such as Key.enter.

KeyEvent.text(text)
KeyEvent.text(text, modifiers)

Construct from exactly one strictly valid UTF-8 scalar. NUL and non-BMP scalars are supported. Empty strings, malformed bytes, and multiple scalars are rejected. No NFC normalization or grapheme segmentation occurs.

KeyEvent.byte(value)

Construct an explicit numeric keypad byte, from 0 through 255.

KeyEvent.doorway(scanCode, enhanced)

Construct a DoorWay scan with an explicit enhanced-key flag.

key

Unicode scalar for committed text, a named Key identifier for other logical keys, or null for raw bytes and DoorWay scans. Native modified C0 letter keys have a lowercase Latin logical identity; keyboard controls Backspace, Tab and Enter retain their named identity. Console protocols can make Ctrl-H/I/M indistinguishable from those controls.

modifiers

Full event-time Mod mask. Combined modifiers and unknown bits are retained; GUI and Alt remain distinct.

codepoint

Original committed Unicode scalar, or null when the event carries no text.

text

Exact UTF-8 committed scalar, or "" when the event carries no text.

byte

Explicit numeric keypad byte, or null.

scanCode / enhanced

DoorWay scan and Bool flag, or null for other event types.

matches(key, modifiers)

Compare logical key and modifiers, ignoring Caps Lock and Num Lock only.

Alt+Keypad entry without a leading zero remains a raw byte in every Wren VM. Leading-zero Unicode entry produces committed Unicode text. The terminal resolves raw bytes using its active remote encoding; Wren UI code must not reinterpret them through the selected display font.

Wren Strings can contain arbitrary bytes. count counts decoded scalars in valid UTF-8, while integer String and codePoints subscripts use byte offsets. Neither count == 1 nor text[0] validates a Unicode scalar. The native text constructor validates the entire byte sequence, including embedded NUL.

Input.unget preserves the full event and its native source type. Forwarding through CTerm.sendKey uses that source, including text, modifiers, raw bytes, physical edges and DoorWay scans; it does not re-enter key hooks.

PhysicalKeyEvent

Represents one physical key press or release edge using the same evdev key code namespace as CTerm’s physical-key reporting protocol. Returned by Input.next() / Input.poll(), passed to Input.pushClaim handlers, and passed to Hook.onPhysicalKey callbacks.

Physical events remain separate from logical keys and committed text. The host does not synthesize a second logical event from a physical press. A backend may subsequently deliver a translated key or committed text; scripts must choose the appropriate stream for a shortcut rather than bind both. Repeated presses retain repeat; releases remain explicit physical events.

Member Description

PhysicalKeyEvent.new(evdev, pressed)
PhysicalKeyEvent.new(evdev, pressed, modifiers, repeat)

Construct a synthetic physical-key edge. evdev must be in the evdev key-code range; pressed is true for press and false for release. The short form uses zero modifiers and repeat=false.

evdev

evdev key code number.

pressed

true for press, false for release.

modifiers

Event-time modifier mask: Shift=1, Control=2, Alt=4, GUI=8, Caps Lock=16, and Num Lock=32.

repeat

true when the backend identified this press as a repeat.

MouseEvent

Represents one normalized SyncTERM mouse event. Returned by Input.next() / Input.poll(), passed to Input.pushClaim handlers, and passed to Hook.onMouse callbacks — every mouse surface uses this same shape.

Member Description

MouseEvent.new(event, startX, startY)
MouseEvent.new(event, startX, startY, modifiers)
MouseEvent.new(event, startX, startY, endX, endY)
MouseEvent.new(event, startX, startY, endX, endY, modifiers)
MouseEvent.new(event, startX, startY, endX, endY, modifiers, bstate)

Construct from raw fields. Five overloads dispatched by arity. Omitted endX / endY default to startX / startY (a zero-extent point event); omitted modifiers defaults to 0; omitted bstate is derived from event — the bit for the button this event is about, per Mouse, or 0 for Mouse.move. The seven-arg form is the canonical fully-explicit constructor.

MouseEvent.withPixels(event, startX, startY, endX, endY, modifiers, bstate, startPixelX, startPixelY, endPixelX, endPixelY)

Construct a fully explicit synthetic event including internal raster coordinates. This is a named factory rather than a sixth overloaded constructor so pixel and cell coordinates cannot be confused by arity.

MouseEvent.withPixelsAndWheel(event, startX, startY, endX, endY, modifiers, bstate, startPixelX, startPixelY, endPixelX, endPixelY, wheelX, wheelY)

The fully explicit factory, including signed wheel-axis values.

event

Mouse event type code.

bstate

Snapshot of the button-state bitmask at the moment the event fired (the bstate field on struct mouse_event). Lets a drag-end handler check which other buttons were also held.

modifiers

Event-time keyboard modifier mask, using the same bits as PhysicalKeyEvent.modifiers. Derived click and drag events retain the modifiers from their button press.

startX, startY

Click-down coordinates (1-based).

endX, endY

Release coordinates (1-based).

startPixelX, startPixelY

Click-down coordinates in the 0-based internal raster. Native backends that cannot report pixel positions use -1. Ordinary MouseEvent.new(…​) constructors initialize these fields to 0.

endPixelX, endPixelY

Release coordinates in the 0-based internal raster, with the same -1 and synthetic-constructor rules as the start fields.

wheelX, wheelY

Signed native wheel magnitude. A vertical event has wheelX=0; a horizontal event has wheelY=0. Diagonal input is returned as vertical then horizontal events.

Mouse event constants

Mouse.button1* through Mouse.button5* identify left, middle, right, X1, and X2 events. Each family occupies nine stable values in the order Press, Release, Click, double/triple/quadruple Click, DragStart, DragMove, and DragEnd. Native translation currently produces Press, Release, Click, DragStart, DragMove, and DragEnd; multi-click values remain available to synthetic input. Mouse.wheelUp, wheelDown, wheelLeft, and wheelRight are values 46 through 49. The older wheel*Press and wheel*Click names remain aliases.

ClaimHandle

Returned from Input.pushClaim. Drop the claim by calling pop().

Member Description

pop()

Remove the claim entry from the stack. Idempotent — stale handles (after a same-fiber re-push bumped the entry’s id, or after another path popped it, or after the foreign finalizer ran) no-op silently. The C-side foreign finalizer also pops on GC, so a forgotten handle still cleans up — but explicit pop is cheaper and more predictable.

Wake

Owner-thread fiber-resume primitive. Wake.post(fiber, value) queues a synthetic resume of fiber, delivering value as the return of its next Fiber.yield(). It is held in that VM’s FIFO and delivered by the owning host’s next explicit wake drain — never in the middle of the current foreign call. It may be called while executing that VM on its owner thread (hooks, claim handlers, and worker fibers). value may be any Wren object — the deliverer pins it as a WrenHandle until delivery, then loads it into the fiber’s resumed-value slot. Multiple posts queue up; each becomes one resumption in arrival order.

Method Description

Wake.post(fiber, value)

Queue a resume. Returns immediately; the wake is dispatched on the next main-loop drain. Convention: pass a discriminated value the fiber’s main-loop demuxer can recognise (a foreign KeyEvent / MouseEvent class, or your own sentinel). Do NOT call from inside another foreign method whose caller is about to re-enter wrenCall (same rule as wrenCall itself — see wren.md §7); hooks and claim handlers are the canonical safe sites.

Key

Named key identifiers occupy 0x110000..0x11ffff, above the Unicode scalar range. They identify keys independently of modifiers. Committed text uses its Unicode scalar directly; for example, U+0100 and Key.up are distinct. Key.quit is a separate sticky host shutdown marker at 0x120000.

Available names are escape, enter, backspace, tab, delChar, up, down, left, right, insert, delete, home, end, pageUp, pageDown, and f1 through f12. delChar represents a native ASCII DEL key, separately from the dedicated Delete key. Modified keys use the same identifier plus an explicit modifier mask; for example, event.matches(Key.tab, Mod.shift) tests Shift-Tab.

Mod

Modifier constants are shift=1, control=2, alt=4, gui=8, capsLock=16, and numLock=32. command selects GUI on macOS and Alt elsewhere for bundled application command policy. Event masks retain the actual modifiers reported by the backend. Applications should match the full mask they intend; Caps Lock and Num Lock may be ignored for shortcuts.

Clipboard

Member Description

Clipboard.text

Read the system clipboard as an NFC string, or return ScreenError. An empty clipboard is an empty String, not an error.

Clipboard.setText(s)

Write a string to the system clipboard; return null or ScreenError.

Codepage

Enum-style class identifying a character-set encoding. Returned by Font.codepage and Font.codepageOf(i) to tell scripts which legacy character encoding a selected font uses. Cells expose Unicode text; these values describe explicit conversions at a legacy byte boundary.

Codepage.encodes_(s) accepts exactly one Unicode codepoint and reports whether the codepage of the selected primary font (Screen.font[0]) can encode it. It returns false when that font is unavailable. It does not consult the process locale.

Codepage.encodeByte(codepage, scalar) explicitly encodes one Unicode scalar using the chosen legacy codepage. The scalar is an integer Number from 0 through 0x10FFFF, excluding surrogates (0xD800 through 0xDFFF), rather than a String. Return a byte Number from 0 through 255, or null when that scalar is unmappable. Native aliases choose the first mapping in the legacy table. There is no normalization, replacement character or dependency on the selected font, connection encoding or locale. For example, Codepage.encodeByte(Codepage.cp1251, 0x0410) returns 0xC0. Wrong types, nonfinite/fractional Numbers, invalid codepages and invalid scalars abort the calling Fiber.

Codepage.decodeByte(codepage, byte) explicitly decodes one legacy display byte to a Unicode String. The codepage must be one of the constants below and the byte an integer from 0 through 255. It uses graphical character meanings for control positions: CP437 byte 1 becomes ☺, byte 0xB3 becomes │, and byte 0 remains NUL. Invalid arguments abort the calling fiber. The result is independent of the selected font, connection encoding, locale, and output mode. For example, a CP437 character picker can assign cell.ch = Codepage.decodeByte(Codepage.cp437, value).

Codepage.decodeByte(codepage, byte, graphicControls) adds a strict Bool choice of native decoding mode. true matches the two-argument display form; false selects semantic control meanings. For CP437, byte 1 then returns U+0001 rather than ☺, byte 0x7F returns DEL rather than ⌂, and byte 0x7C returns | rather than ¦. The native tables determine the remaining mappings; byte 0 can return a one-byte NUL String. Invalid arguments abort the calling Fiber. Encoding and decoding are not promised to be inverse operations for every table.

Codepage.brokenVertical(codepage) returns the native compatibility Bool for a valid Codepage constant. It describes the broken-bar display glyph at byte 0x7C, not gaps in box-drawing lines. A _b suffix identifies an explicit broken-vertical variant; some other codepages, including CP437, also have the flag. A false flag does not imply that an arbitrary loaded raster has an unbroken bar. Invalid arguments abort the calling Fiber.

These conversion and metadata methods are synchronous and available in all three VMs. They retain no inputs and grant no file or terminal authority.

Constant Index Description

cp437

0

IBM PC code page 437 — English plus box-drawing. The default for traditional ANSI BBSes.

cp1251

1

Windows-1251 — Cyrillic (Russian, Bulgarian, Ukrainian, etc.) in a "swiss" font variant.

cp1251_b

2

Windows-1251 with the broken-vertical glyph variant.

koi8r

3

KOI8-R — Russian Cyrillic. Common on 1990s Russian Linux/Unix systems.

iso8859_2

4

ISO-8859-2 (Latin-2) — Central European (Polish, Czech, Hungarian, …).

iso8859_4

5

ISO-8859-4 (Latin-4) — Northern European / older Baltic. 9-bit-mapped wide-glyph variant.

cp866m

6

CP866 — Russian DOS, "(c)" modified variant.

iso8859_9

7

ISO-8859-9 (Latin-5) — Turkish.

iso8859_8

8

ISO-8859-8 — Hebrew.

koi8u

9

KOI8-U — Ukrainian Cyrillic.

iso8859_15

10

ISO-8859-15 (Latin-9) — Western European with the Euro sign.

iso8859_5

11

ISO-8859-5 — Latin/Cyrillic.

cp850

12

CP850 — Multilingual Latin-1 (DOS Western European).

cp850_b

13

CP850 with the broken-vertical glyph variant.

cp865

14

CP865 — Nordic DOS (Danish, Norwegian).

cp865_b

15

CP865 with the broken-vertical glyph variant.

iso8859_7

16

ISO-8859-7 — Greek.

iso8859_1

17

ISO-8859-1 (Latin-1) — Western European, classic Unix default.

cp866m2

18

CP866 — Russian DOS, second modified variant.

cp866u

19

CP866-U — Ukrainian variant.

cp1131

20

CP1131 — Belarusian DOS.

armscii8

21

ARMSCII-8 — Armenian.

haik8

22

HAIK-8 — older Armenian set; used with the ARMSCII-8 screen map.

atascii

23

ATASCII — Atari 8-bit native character set.

petsciiUpper

24

PETSCII (uppercase/graphics mode) — Commodore 64/128 default.

petsciiLower

25

PETSCII (lowercase/shifted mode) — Commodore 64/128 after a Shift+Commodore key.

prestel

26

UK Prestel / Viewdata teletext — block mosaic graphics, double-height, conceal.

prestelSep

27

Prestel separated mosaics — block mosaics with gaps between cells.

atariSt

28

Atari ST GEM character set.

Cell

Wraps one st_console_cell: its resolved drawable glyph/font, colours, source attributes, flags, and hyperlink. Read a Surface through Screen.readRect, edit its cells, and blit it back through Screen.putRect.

The three-argument Surface.cellAt(x, y, cell) overload can retarget the same Cell object to successive cells of a Surface. This changes what storage that object refers to; it does not copy cell contents.

Member Description

Cell.new()

Construct an empty cell.

ch, ch=(s)

Character as one NFC extended grapheme cluster. Assignment accepts exactly one valid cluster, normalizes it to NFC, then resolves one drawable glyph in the selected font and Unicode fallback font. An unsupported cluster is one missing glyph, including emoji modifier sequences that do not use ZWJ. + Unlike ordinary text output and Screen.textWidth, an explicit zero-width cluster assignment requests a diagnostic glyph. A narrow mapping is used as is (including a blank NUL mapping). A wide diagnostic is allowed only when this Cell refers to a Surface with another column available in the same row; otherwise a narrow missing glyph is used. Missing mappings also use narrow tofu. Assignment preserves the selected font, colours, attributes, and hyperlink, and repairs overwritten wide pairs.

font, font=(n)

Font catalog selector at the Wren boundary. The selected and actual glyph font identifiers are retained separately in stored cells. Assignment resolves the current Unicode text in the new font and its fallback. Cell creation, character assignment, and font changes perform no legacy byte conversion.

legacyAttr, legacyAttr=(n)

Legacy attribute byte (foreground in low nibble, background in high nibble, plus source bright/blink bits). Setting it marks both colours as legacy-derived. The active VideoFlags decide whether those source bits also select bright colours, blink, or alternate font slots when a new screen cell is written. Explicit fgPalette, bgPalette, fgRgb, or bgRgb assignment replaces the corresponding legacy-derived colour; legacyAttr then reports its nearest active-palette representation while retaining the source bright/blink bits.

bright, bright=(b)

Source attribute bit 3. This is distinct from the bold drawing style.

blink, blink=(b)

Blink bit.

fastBlink, fastBlink=(b)

Selects the fast cadence when blink is enabled.

strikethrough, strikethrough=(b)

Draws a one-pixel foreground line across the centre row of an odd-height cell or the lower middle row of an even-height cell.

overline, overline=(b)

Draws a foreground line across the top pixel row of the cell.

doubleUnderline, doubleUnderline=(b)

Draws the bottom pixel row and the row two pixels above it when present. Enabling either underline style replaces the other.

underline, bold, reverse, conceal

Read/write Boolean drawing styles. Single underline spans the inked rows of the font’s underscore; bold thickens the glyph; reverse exchanges foreground/background when drawn; conceal hides the glyph unless its retained reveal flag is set. Bold is independent of the source-bright attribute. All style setters require Bool; wrong types abort rather than being ignored.

styleFlags, styleFlags=(mask)

Read or replace the drawing styles together using CellStyle bits. The getter returns only these bits. Assignment requires a finite, exact, nonnegative integer containing no other bits; invalid input aborts before mutation. A mask containing both underline bits selects double underline. This edits only the addressed stored Cell, preserving colours and their origin markers, glyphs, fonts, hyperlinks, wide-cell structure, captured pixels and serial metadata. It does not update neighbouring cells or the terminal’s parsing state.

teletext, doubleHeight, reveal, separated

Read-only Booleans reporting retained SAA5050/teletext presentation state: serial-attribute mode, double height, reveal concealed content, and separated mosaics. These are observations, not independent serial-attribute controls.

teletextControl

Read-only retained seven-bit source control as a Number, or null when none is recorded. Changing serial attributes requires editing the source stream and reconstructing the affected line or screen; Cell does not provide that operation.

pixelGraphics

Read-only. true when pixel drawing has marked this text cell as containing raster data. A captured Surface retains optional row rasters separately from its cells. Cell itself carries only the flag; use Surface rectangle copies to preserve the image. Assigning Cell.ch or filling text cells replaces their captured pixels.

fgPalette, bgPalette

Foreground / background palette indices.

fgRgb, bgRgb

Foreground / background as 24-bit RGB. Setters change only the selected colour channel and its legacy-derived marker; source bright/blink and all other cell state remain intact.

hyperlinkId, hyperlinkId=(n)

Hyperlink ID attached to this cell.

eqContent(other)

Structural equality of every content field. This is not a == override — cell == otherCell stays foreign-identity-based, like every other foreign in the API. Call eqContent explicitly when you want to know "do these two cells have the same content?" (e.g. `surf.where {

c

c.eqContent(template) }`). + Returns false for non-Cell other (no fiber abort) and when either cell has the pixel-graphics flag, because the pixel planes are not part of a Cell. Otherwise it compares the drawable glyph and its owning font, colours, public flags, selected font, and hyperlink. + Note that Cell cannot be a Map key — Wren’s Maps reject any foreign object regardless of == definitions (wren_value.h:880-888). Defining a structural == would not lift that restriction; that’s why we expose this as a named method instead.

CellStyle

Named masks for Cell.styleFlags, available in all script VMs. bright is 0x400000, blink is 2, underline is 0x10000, bold is 0x20000, reverse is 0x40000, conceal is 4, fastBlink is 0x2000000, strikethrough is 0x4000000, doubleUnderline is 0x100000, and overline is 0x200000. all is their union (0x6770006). These native bit values fit Wren’s ordinary bitwise operators. Renderer state, serial attributes and pixel-graphics ownership are excluded from this mask.

cell.bold = true
cell.styleFlags = CellStyle.bold | CellStyle.underline

Surface

A width × height grid of Cells backed by a contiguous st_console_cell buffer. Surface is Sequence, so the linear [i] subscript, count, and the standard sequence helpers (each, where, map, all, any, reduce, join, take, skip, toList, …) all work — handy for "tell me where any 'X' lives" without switching to 2D indexing. Linear order is row-major: buf[y * width + x].

Screen.readRect returns a Surface sized to the requested rect, with optional pixel strips for rows containing graphics. Captured strips retain RGB colours and both blink phases; plain-text rows allocate no pixel storage. Rectangle copies, including clipped and overlapping self-copies, preserve those strips. Glyph edits and text fills replace the affected cells' raster content; style edits do not recolour captured pixels. Screen.putRect restores cells and pixel-marked regions in one presentation batch, so UI overlays remain visible. The UI library uses Surfaces as per-widget backbuffers and composites them into a screen-sized backbuffer Surface that’s blitted once per frame.

Member Description

Surface.new(width, height)

Allocate a fresh Surface of the given size. Cells start as spaces using the current screen style.

width, height

Dimensions in cells.

count

width * height — total cell count. From the Sequence protocol.

[i]

Linear-indexed read of the cell at offset i. Returns a Cell view onto the Surface’s buffer (mutating the cell mutates the Surface).

cellAt(x, y)

2D-indexed Cell view (0-based). Returns null if (x, y) is outside [0, width) × [0, height).

cellAt(x, y, cell)

Retarget an existing Cell view to (x, y) without allocating another Wren object. Returns true on success. If (x, y) is outside the Surface, returns false and leaves cell unchanged. This form is intended for drawing and scanning loops; because the same object is mutated on each call, do not retain it as a reference to an earlier position.

iterate(it), iteratorValue(it)

Sequence protocol — yields each cell linearly in row-major order (the cell at (x, y) appears at iteration index y * width + x).

rows

Sequence-of-Sequence view, outer-by-y. surf.rows has length surf.height and yields SurfaceRow instances; each row has length surf.width and yields Cell`s left-to-right. Use for the natural row-major nested loop: + [source,wren] ---- for (row in surf.rows) { for (cell in row) …​ } ---- + Single-cell access: `surf.rows[y][x] (equivalent to surf.cellAt(x, y)).

cols

Sequence-of-Sequence view, outer-by-x. surf.cols has length surf.width and yields SurfaceCol instances; each column has length surf.height and yields Cell`s top-to-bottom. Use when column-major traversal reads cleaner: + [source,wren] ---- for (col in surf.cols) { for (cell in col) …​ } ---- + Single-cell access: `surf.cols[x][y]. + Both rows and cols are lazy views — they hold a reference to the Surface and fetch cells on demand via cellAt, so mutating a cell through surf.rows[y][x] mutates the underlying Surface.

urlAt(x, y)

Detect an ASCII HTTP, HTTPS, FTP, FTPS, or bare www. URL at a zero-based cell position. Returns the URL or null; bare www. receives an https:// prefix. Detection follows text across a filled row boundary and trims trailing punctuation while preserving balanced parentheses/brackets. Cell text is resolved through its actual font mapping.

putRect(src, dstX, dstY), putRect(src, srcRect, dstX, dstY)

Paste a source Surface into this Surface at (dstX, dstY) (0-based). The 4-arg form copies a sub-rect of src defined by a Rect. Out-of-bounds writes are clipped. Source and destination may be the same Surface; overlapping copies behave as though the clipped source were read before any destination cell changed. If clipping selects only half of a two-cell glyph, that incomplete glyph becomes a styled blank.

fill(rect, cell)

Bulk-fill the intersection of rect (a Rect) and the Surface with a copy of cell. The cell must occupy exactly one column; a wide or continuation cell aborts the calling fiber without changing the Surface. Empty and disjoint rectangles are no-ops.

toString

Debug-only string form, e.g. "Surface(80x25)". Format may change.

Scrollback

Read-only logical access to the active cterm scrollback ring. The ring stays in its native wrapped representation: these methods do not append rows, rotate storage, or change CTerm.scrollbackStart / scrollbackPos. SkyPix pixel scrolling can leave an unfinished strip between complete rows and the live screen. Reads compose it into rows aligned at the live boundary, within the configured capacity. A change of geometry finishes the strip in its original grid. Any padding precedes that run of rows. Pixel colours and both phases were captured when they left the screen, so a later palette change does not recolour the pending strip. Row copies do not flush it. Aligned cell text is preserved; a fractional row view carries pixels with blank cell metadata rather than stale text at the wrong position.

Member Description

width

Current projection width in cells, or zero when no ring exists.

height

Number of retained logical history rows, or zero when no ring exists.

rowGeometry(index)

Return [columns, cellWidth, cellHeight] in the original geometry. Index zero is the oldest row. The live terminal page follows the retained rows at height. An index past the live page returns null.

row(index)

Return an owned, one-row Surface at its original width, with font, glyph, hyperlink and available bitmap data. The indexes match rowGeometry. Call surface.drawHistoryRow(left, x, y, width, height) to draw a clipped portion from horizontal offset left at the zero-based destination. Bitmap consoles use native pixels on both axes. Text consoles use columns and rows. Read errors return ScreenError.

copyRowsTo(destination, sourceRow, rowCount, destRow)

Copy whole logical history rows, oldest-first, into an owned Surface. Source and destination row ranges are clipped; the return value is the number of rows copied. Physical ring wrap is translated per row without changing the ring. The copy projects older rows to the current width, clipping wider rows and padding narrower ones. Optional captured pixel strips are copied only for requested rows and survive subsequent ring overwrite. Native cell/pixel-copy failures return ScreenError; check the result before use. Work and image memory depend on the requested viewport, rather than the configured scrollback capacity.

Font

A "font" in SyncTERM is one of 257 indexed slots, each a complete glyph table for a particular character set or display style. Slots 0–45 ship with built-in fonts, covering the codepages enumerated by Codepage plus several Amiga and 8-bit display styles. Slots 46+ hold configured or remotely supplied fonts. Font.count reports the current catalog extent; use Font.available(i) to determine whether a catalog slot has a bitmap for the active cell dimensions.

Application UI uses system CP437, independently of the connection’s font. Font.cp437English remains the system font for Wren drawing even when SkyPix or a remote command replaces terminal slot zero. The status bar, online menu, file picker and transfer dialogs use it; built-in/loaded theme snapshots resolve explicit font choices to system CP437. SkyPix keeps the screen mode’s system cell grid independent of the Amiga strike: at 640x200 UI uses 8x8 CP437 even with Diamond 20. The console scales a system strike only when the chosen screen-mode cell dimensions have no exact system strike. Text backends retain Unicode presentation and use their external terminal’s font.

The Font class itself only exposes named constants for the most useful slots; every slot is reachable numerically through Screen.font[i] regardless. The full built-in table follows.

Named constant Index Slot description

Font.cp437English

0

Codepage 437 English (default).

1

Codepage 1251 Cyrillic, "swiss" variant.

2

Russian KOI8-R.

3

ISO-8859-2 Central European.

4

ISO-8859-4 Baltic wide (VGA 9-bit mapped).

5

Codepage 866 (c) Russian.

6

ISO-8859-9 Turkish.

7

HAIK-8 (used with the ARMSCII-8 screen map).

8

ISO-8859-8 Hebrew.

9

Ukrainian KOI8-U.

10

ISO-8859-15 West European, "thin" variant.

11

ISO-8859-4 Baltic (VGA 9-bit mapped).

12

Russian KOI8-R, alternate (b) variant.

13

ISO-8859-4 Baltic wide.

14

ISO-8859-5 Cyrillic.

15

ARMSCII-8 (Armenian).

16

ISO-8859-15 West European.

17

Codepage 850 Multilingual Latin I, "thin".

18

Codepage 850 Multilingual Latin I.

19

Codepage 865 Norwegian, "thin".

20

Codepage 1251 Cyrillic.

21

ISO-8859-7 Greek.

22

Russian KOI8-R, alternate (c) variant.

23

ISO-8859-4 Baltic.

24

ISO-8859-1 West European.

25

Codepage 866 Russian.

26

Codepage 437 English, "thin" variant.

27

Codepage 866 (b) Russian.

28

Codepage 865 Norwegian.

29

Ukrainian CP866-U.

30

ISO-8859-1 West European, "thin".

31

Codepage 1131 Belarusian, "swiss".

Font.commodore64Upper

32

Commodore 64 (uppercase / graphics).

Font.commodore64Lower

33

Commodore 64 (lowercase / shifted).

Font.commodore128Upper

34

Commodore 128 (uppercase / graphics).

Font.commodore128Lower

35

Commodore 128 (lowercase / shifted).

Font.atari

36

Atari 8-bit.

Font.potNoodle

37

P0T NOoDLE — Amiga BBS classic.

Font.mosOul

38

mO’sOul — Amiga BBS classic.

Font.microKnightPlus

39

MicroKnight Plus — Amiga.

Font.topazPlus

40

Topaz Plus — Amiga.

Font.microKnight

41

MicroKnight — Amiga.

Font.topaz

42

Topaz — Amiga Workbench font.

Font.prestel

43

Prestel — UK Viewdata mosaic.

Font.atariSt

44

Atari ST GEM.

Font.ripterm

45

RIPterm — RIP graphics terminal font.

The "thin" variants are the same character set rendered with thinner strokes in the VGA BIOS style. A "swiss" variant uses a Helvetica-style sans rendering. An "(a)" / "(b)" / "(c)" annotation distinguishes bundled font variants that use the same codepage encoding.

Method Description

Font.name(i)

Human-readable font name for slot i, e.g. "Codepage 437 English". Returns the empty string for empty slots.

Font.count

Current catalog extent. 0…​Font.count walks every built-in and configured slot; use Font.available(i) to skip unavailable bitmaps.

Font.available(i)

true if slot i has actually been loaded (the user can configure SyncTERM to omit some built-ins).

Font.builtinBrokenVertical(selector)

Native static broken-vertical compatibility flag of a built-in selector (0 through 45). Available in all three VMs, even if its bitmap is unavailable. This describes the bundled catalog entry independently of configured, downloaded or session raster replacements; it does not inspect a live font. Custom selectors, wrong types and nonfinite/fractional/out-of-range Numbers abort the calling Fiber.

Font.codepage

Actual mapping of the font selected in Screen.font[0], or null if its bitmap is unavailable.

Font.codepageOf(i)

Actual mapping of the font selected in script-output slot Screen.font[i] (0 through 4), or null if unavailable.

Font.codepageFor(selector)

Actual mapping of the registered catalog selector (0 through 255), or null if unavailable. This argument is a font selector, whereas codepageOf takes a script-output slot.

Font.load(file)

Register a 256-glyph bitmap using the terminal’s current CTerm.codepage, including its legacy fallback during UTF-8 operation.

Font.load(file, codepage)

Register with an explicit Codepage value.

Both load forms return the allocated selector (46 through 255), a FileError for a file access/read failure, or a FontError. Loading requires an active terminal and ScreenSupports.loadableFonts. It reads an actual readable File grant belonging to the calling VM; path Strings are rejected. Revoked/stale read authority returns FileError with IOErr.permissionDenied. Loading neither selects the font nor changes the File’s stream position, consumes its grant, or saves settings. The bitmap remains usable after the File is closed or collected. Failed loads publish no catalog entry. Configured selectors and selectors occupied by downloaded font variants are reserved.

The default mapping is captured at load time from CTerm.codepage; it does not follow Screen.font, the process locale, or later terminal encoding changes. The explicit overload accepts the serialized Codepage enum, not a text label or UTF-8 encoding sentinel. An unsupported mapping is a font failure. Font files contain raw bitmap bytes, never normalized text. Their dimensions must match the current console cell, with exactly 256 glyphs.

var selector = Font.load(file, Codepage.cp1251)
if (selector is Error) return selector
CTerm.font[0] = selector

FontError

FontError is Error reports font failures separately from file failures. It has read-only code, nativeCode, message, and toString properties and no public constructor. nativeCode preserves the underlying portable native I/O status, or zero when no native operation failed. Its diagnostic starts with FontError.

FontErr value Code Meaning

unavailable

1

No active terminal or the backend cannot load/select fonts.

invalidBitmap

2

The bitmap size or dimensions are invalid.

unsupportedCodepage

3

No bitmap mapping is available for the codepage.

noSlots

4

No free custom selector remains.

notLoaded

5

The requested selector has no available registration.

nativeFailure

6

Another native font/registration operation failed.

Wrong types, inexact/out-of-range numbers, invalid codepage enums, invalid assignment indices, and invalid masks are programmer errors and abort the calling Fiber. Recoverable load failures are returned as Error values.

Typed-ID lookup table over the application-lifetime hyperlink registry. It is available to the menu and connected VMs, but not the file-picker VM. Despite the [id] / containsKey(id) shape, this is not a Map — there is no keys / values / count / iteration. IDs flow into a script from add() returns or from Cell.hyperlinkId on cells under the cursor; scripts can’t enumerate the ID space. IDs range from 1 through 65535 and zero means no hyperlink. IDs attached to live console cells, Wren Cell/Surface storage, terminal scrollback, or retained session history remain stable. If the registry fills, IDs not reachable from those roots may be reclaimed and reused. Consequently, scripts should resolve or attach an ID promptly rather than treating a detached number as permanent application-lifetime storage.

Member Description

Hyperlinks[id]

URI string for id, or null if id is not in the table.

Hyperlinks.containsKey(id)

true if id is present.

Hyperlinks.add(uri, idParam)

Allocate a hyperlink ID for uri with optional id parameter string. A non-empty parameter deduplicates an exact URI/parameter pair. A null or empty parameter always allocates a fresh ID. Returns zero if the registry is full or the value cannot be stored.

Hyperlinks.params(id)

Parameter string for id, or null.

To attach hyperlinks to text, allocate an ID and assign it to Screen.hyperlinkId before writing through Screen.window.print.

Console

Read-only access to the current VM’s always-on print/error log buffer. The buffer has 1024 entries of up to 8 KB each; older entries are evicted in FIFO order. Sequence numbers are monotonic across the VM’s lifetime, including across eviction, so an incremental "show only entries newer than X" reader works correctly even after the ring has wrapped.

Member Description

Console.count

Number of valid entries currently in the ring.

Console.total

Monotonic count of entries ever written. Survives clear().

Console[seq]

Entry with monotonic sequence seq, as a [ts, source, text] triple (the seq number is the index you queried with — not duplicated in the value). source is one of the LogSource values. Out-of-range returns null.

Console.clear()

Drop all entries. total keeps incrementing.

Console.markSeen()

Snapshot the current total and error counters as the "seen" baseline. The connected status-bar indicator and menu top-right indicator (yellow for new prints, red for new errors) compare the live counters against this baseline, so calling markSeen() clears the indicator until the next entry arrives. The built-in REPL invokes this on exit so console activity logged while the REPL is open doesn’t leave the indicator lit.

Console.iterate, iteratorValue

Wren iteration protocol — works in for (e in Console) { …​ }.

Console.entries

Sequence-protocol view on the same underlying buffer. Returns a fresh ConsoleEntries instance that delegates count, [seq], and the iteration pair to Console. Use this when you want .map/.where/.toList/.count/.where/etc. — the helpers are defined as instance methods on Sequence, so they need an instance to dispatch on: + [source,wren] ---- var errors = Console.entries.where {

e

e[1] == LogSource.runtimeError }.toList ---- + Console itself stays an all-static namespace — it can’t is Sequence directly because Sequence’s helpers (map, where, …​) are defined as instance methods on this, which a class object can’t satisfy.

LogSource

Enum values for the source field on Console entries.

  • LogSource.print (0) — script System.print.

  • LogSource.compileError (1) — Wren compile diagnostic.

  • LogSource.runtimeError (2) — Wren runtime error message.

  • LogSource.stackFrame (3) — one frame of a runtime-error stack trace.

REPL

Primitive for the immediate-mode REPL. Most scripts will not use this directly; the embedded wren_console script wraps it.

Method Description

REPL.eval(src)

Compile and run src in module syncterm. Returns null for statements; [value] (a one-element list) for expressions.

REPL.eval(module, src)

As above, in module.

REPL.hasModule(name)

true if name has been loaded.

REPL.modules

List of every module name currently loaded in the VM (including core). Order is implementation-defined; sort if you need stable output.

The [value] wrapper for expressions distinguishes "this was a statement" from "this was an expression whose value is `null`".

Runtime errors propagate normally. Wrap the call in Fiber.new {}.try() to catch them.

Session

Session.current is the stable VM-scoped view of the connected session, or null in menu/picker VMs and during session teardown. Session lifetime holds belong to independent SessionLease objects, separately from terminal state.

Member Description

Session.current.profile

Stable read-only Profile snapshot of the connection configuration. Its copy() creates an independent editable Profile.

Session.current.name

Captured connection name.

entryId, entrySource

Captured directory ID and BBSListType provenance. A transient connection has ID -1.

added, lastConnected, calls

Captured entry timestamps and connection count. These are metadata, not editable Profile fields.

Session.current.runDos(path), Session.current.runDos(path, arguments)

Run an installed DOS door terminal on the active connection. Use an absolute S:\ path to an .EXE with DOS 8.3 path components. The program starts in its own directory. The optional String supplies the DOS command tail as up to 125 bytes, without NUL, CR or LF. COM1 uses the entry’s baud rate from 50 through 115200, defaulting to 9600. The call returns when the guest exits, the carrier drops, or the user presses Ctrl-Esc. Zero indicates the emulator returned normally or was stopped. Launch and I/O failures return a negative IOErr code.

Session.current.hold()

Acquire a lease that keeps the session pumping after shell EOF while its owner has auxiliary work. A lease cannot release another owner’s hold. Native pending SFTP requests also keep their work alive independently.

Session.current.hold(fn)

Run fn with a scoped lease. Returns the callback result and releases the lease on return or abort, preserving cooperative yields and the original error. VM shutdown releases the hold without resuming parked work.

Session.current.holdCount

Number of live script leases; excludes native pending requests.

SessionLease.release()

Release this hold. Returns true once, then false on repeated calls.

SessionLease.released

Whether this lease has been released explicitly, by GC, or during shutdown.

Install door terminals and their data files under the SyncTERM data directory’s dosbox-x subdirectory. Connected DOS sessions mount it read-only as S:. Configure clients that save settings there from Settings > DOS Shell. Any graphics profile can launch a local terminal on a bitmap display when libdosbox is available and safe mode is off.

To enable automatic launch for a particular BBS, manually copy the corresponding add-on from the source tree (addons/lod_gterm.wren or addons/pit_terminal.wren) into the SyncTERM data directory’s scripts/ subdirectory, then select it for that personal dialing entry.

For Land of Devastation 5.11, install GTERM and its data files in dosbox-x/LOD and set WrenScripts = lod_gterm in the personal dialing entry’s INI section. The script starts GTERM on the stock welcome line so it can answer the door’s version probe (5C 47 45 08) on COM1. If the welcome line is absent, the first probe starts GTERM. Press Enter at the main or wasteland menu to have the door probe again. Ctrl-Esc returns to SyncTERM, and later menu probes leave it there until the next welcome or reconnection.

To start GTERM manually, enter these lines in the connected Wren Console.

var door = Session.current
door.runDos("S:\\LOD\\GTERM.EXE", "COM 1 BAUD 9600")

For The PIT! 4.17, extract the terminal archive PIT417_T.ZIP into dosbox-x/PIT417 so it contains PTERM.EXE, its configuration and its data files. Set WrenScripts = pit_terminal in the personal dialing entry’s INI section to enable the add-on. It watches for the door’s graphics terminal invitation and launches PTERM on COM1 at the session baud rate. Press any key at PTERM’s startup screen to connect to the door. To start it manually, use door.runDos("S:\\PIT417\\PTERM.EXE", "1 9600").

While DOS owns COM1, SyncTERM pauses terminal parsing. Unread bytes remain available when the terminal resumes. A wire or input hook runs during byte dispatch and cannot take ownership there. A pending script send, wire lease or file transfer can also return IOErr.busy.

Leases are host-created and have no public constructor. Keep the lease reachable while it is needed; collecting an abandoned lease releases its hold. Explicit disconnect and actual connection loss still end the session. The bundled SFTP queue owns a lease while it has runnable work; the public-key installer uses a scoped lease. Neither client controls the other’s lifetime.

Conn

Connection-level send and receive.

Member Description

Conn.sendText(s)

Queue Unicode text using the session’s wire encoding and transport processing (including Telnet IAC escaping or MQTT framing). Returns an Operation; .await() returns null when all output has entered the transport queue, or a ConnError on failure. This acknowledges local queueing, not remote receipt. The whole input is validated and NFC-normalized before output. Codepage sessions reject any unmappable scalar; malformed or unmappable text sends nothing and does not beep. UTF-8 and embedded NULs are preserved after normalization.

Conn.sendBytes(s)

Queue the String’s exact bytes, including malformed UTF-8, NUL and CR/LF, applying transport framing (Telnet IAC and NVT CR escaping, MQTT framing). No Unicode conversion, text newline folding or local XON/XOFF interpretation occurs. Returns an Operation with the text send completion contract.

Conn.close()

Close the connection.

Conn.endSession(exitApp)

Request a session end. Sets a flag that doterm() picks up at the top of its next iteration, runs the (UI-free) cleanup (cterm shutdown, conn close, mouse/cursor restore), then either returns to the main menu (exitApp == false, Alt-H / Ctrl-Q semantics) or exits syncterm entirely (exitApp == true, Alt-X semantics). Returns immediately — the caller is responsible for any user-facing confirm popup. The default disconnect-key hooks in keys_default.wren raise a Wren-side Confirm popup before invoking this; the online_menu Disconnect / Exit entries call this directly (the menu selection is itself the confirmation).

Conn.paste()

Paste from the system clipboard onto the wire — codepage-aware, bracketed-paste-aware. No-op when the clipboard is empty. This is the operation bound to Shift+Insert by the default key hooks.

Conn.scrollback()

Invoke ScrollbackView.run() in the connected VM. The Wren view composes each terminal-sized viewport from read-only logical ring rows plus a terminal-sized capture of the live screen. It supports keyboard, mouse, selection, URL, and help interaction, then restores the live terminal and exact previous mouse-event mask on exit. The history ring is never appended, rotated, or copied in full. While active, the viewer replaces remote tracking subscriptions with only the mouse events used by the viewer. This is the default Alt+B path.

Conn.connected

Bool — is the link up?

Conn.elapsedSeconds

Monotonic seconds since the connection provider reached the active connected state, clamped to 0. This is live connection/session state; Session.current.lastConnected is the persisted wall-clock LastConnected timestamp from the BBS list.

Conn.type

ConnType value.

Conn.sessionLog

A String snapshot of the current application’s session log, including protocol, CTerm, and transfer messages accepted by their respective log levels. It is independent of the optional log filename and contains only this connection’s diagnostics. The application retains up to 1 MiB of recent records, discarding whole old lines when needed. An empty log is ""; hosts without a session-log provider return null. This is separate from the Wren print/error console. Reopening the viewer takes a new snapshot.

Conn.queued

Bytes in the transport output ring that have not gone out yet. This does not include the unsent storage owned by pending send Operations.

Owned terminal-channel I/O

Session.current.claimWire() returns a WireLease, or a ConnError when another owner, native transfer, transfer reservation, pending script send or active terminal input callback prevents acquisition. Await earlier sends before claiming. This is terminal-channel input after transport decoding, not access to encrypted network packets. Native terminal display and output, key forwarding and other script sends pause while it is owned. UI dispatch continues. CTerm.suspended is independent and retains its previous value.

Member Description

available

Number of available bytes in FIFO order: returned transfer input, unread terminal read-ahead, then the connection queue.

readBytes(count)

Consume up to 65536 bytes; nonempty String on data, "" when nothing is ready, null at drained EOF, or ConnError on failure. Zero returns "" without reading. Consumed input is captured once.

peekBytes(count)

Same results and limits without consumption or capture.

sendBytes(bytes)

Framed binary payload Operation, as for Conn.sendBytes.

sendWire(bytes)

Deliberately bypass transport framing and text conversion. Use only for a protocol that requires such bytes; MQTT payloads require sendBytes.

release()

Idempotent Bool; cancel pending owned sends and return unread input to terminal processing in order. Already queued output stays queued.

released

Bool.

use(fn)

Call fn with this lease, releasing on return/error and across cooperative yields, preserving the callback’s result or error.

Send failure, drained EOF, read failure, GC and VM/session teardown release the lease. An input capture failure can consume bytes before reporting its error. A pending send retains its owner until completion or cancellation. A released lease returns ConnError for input and failed Operations for output; claim a new lease for later work. A live lease alone does not keep a disconnected session alive; use Session.hold when auxiliary work must finish after EOF. The old unowned Conn receive/peek/pending and sendRaw entry points are removed.

ConnError

Conn.sendText and Conn.sendBytes own the remaining output and retry queue pressure internally. Requests run in FIFO order within the VM. At most 64 pending requests and 1 MiB of owned encoded storage (including terminators) are allowed; an individual input must be smaller than 1 MiB. Oversized or excess requests complete immediately with ConnErr.queueFull and send nothing. Text is submitted in complete encoded scalar units. Other terminal writers may run between those units; await completion before sending a key or starting a protocol that must follow the text.

Cancellation discards the unsent remainder and completes with the usual OperationError. Bytes already queued cannot be recalled. Dropping an Operation handle does not cancel its send. Shutdown cancels pending sends. File-transfer ownership rejects new or pending sends with ConnErr.busy. A WireLease rejects sends from Conn; use the lease for protocol output.

Recoverable connection failures complete the Operation with ConnError:

Member Description

code

ConnErr.* enum value.

partial

Bool: some of this request was accepted before the failure. This is diagnostic, not an input offset. Do not resend a whole request after a partial failure unless duplication is acceptable.

message

Human-readable diagnostic.

toString

"ConnError: <CODE-NAME>: …​".

ConnErr constants:

Constant Code When emitted

ConnErr.notConnected

1

The connection is down.

ConnErr.io

2

The transport rejected the remaining output.

ConnErr.queueFull

3

The script request/storage limit was reached.

ConnErr.invalidText

4

Malformed UTF-8 or text unrepresentable in the session’s codepage. No output from this request was queued.

ConnErr.busy

5

A wire lease or file transfer owns or has reserved the connection.

var error = Conn.sendText("café").await()
if (error == null) {
  CTerm.sendKey(KeyEvent.new(Key.enter))
} else {
  System.print(error)
}

As with other Operations, a hook with a synchronous return contract must start a child Fiber to await completion; an App handler uses app.runChild.

Capture

Streaming-log control for the active session. The Wren-side CaptureMenu in scripts/auto/connected/capture_menu.wren implements the user-facing Alt+C flow with these primitives. All methods are no-ops when no terminal is active.

Method Description

Capture.active

Bool — true while a streaming log is open (regardless of pause state).

Capture.paused

Bool — true when the active log has been paused via Capture.pause(). Bytes still flow through cterm; just nothing gets written to the log file.

Capture.start(file, raw)

Open a streaming log to the path authorized by file (a write-consent File from Host.pickSavePath). raw == true captures the original received connection bytes before wire hooks, RIP conversion, character decoding, and semantic input hooks. This preserves codepage bytes, malformed or incomplete UTF-8, escape sequences, and opaque payloads exactly. It captures the terminal stream after transport processing (such as SSH decryption or Telnet negotiation). false captures decoded UTF-8 after semantic input hooks and omits protocol bytes and ESC markers. Macro playback is not captured a second time; locally injected UTF-8 appears only in plain-text capture. Consumes the File’s write consent. Returns null on success or a FileError on open failure (typically errno = EEXIST for WFC_CREATE if the path was created between pick and open). Aborts the fiber on programmer error (already capturing, no consent on file, etc.).

Capture.stop()

Close the active log. No-op when not capturing. Idempotent.

Capture.pause()

Set the PAUSED bit on the active log. No-op when not capturing or already paused.

Capture.resume()

Clear the PAUSED bit. No-op when not capturing.

Use CTerm.saveScreenshot for a one-shot binary screen snapshot with optional SAUCE metadata. Screen snapshots are terminal state rather than streaming logs and therefore are not part of Capture.

CTerm

The active terminal’s state and local operations. Most state properties are read-only. Useful from Hook.onInput and Status.callable for emulation-aware logic. Terminal operations are available in the connected VM.

For RIP3, these properties and local operations address the selected virtual text window. Its cursor and dimensions are independent of the main Screen canvas, which retains the entry’s configured video mode. CTerm.write and CTerm.reset present their local changes inside that window.

Group Members

Cursor (1-based, on the terminal)

x, y

Origin (1-based, on the host screen)

originX, originY

Geometry

width, height, topMargin, bottomMargin, leftMargin, rightMargin

Color state

attr, fgColor, bgColor, hasPaletteOverride, paletteOverride

Fonts

fontSlot, font, setFont(selector, mask)

Scrollback

scrollbackLines, scrollbackWidth, scrollbackPos, scrollbackStart

Mode flags

emulation (Emulation), doorwayMode, music / music = i (MusicMode enum; setter clamps out-of-range values), started, graphicsMode (read-only GraphicsMode), skypix (true for either SkyPix variant), statusDisplay (StatusDisplay), atasciiInverse (Bool — ATASCII inverse-video mode), ooiiMode (0 = off, 1..3 = OOTerm / OOTerm1 / OOTerm2). Streaming-log state moved to the Capture class.

Screenshot

saveScreenshot(file, withSauce) — write the cterm area (status bar excluded) as IBM-CGA / BinaryText to file (a write-consent File from Host.pickSavePath), optionally appending a SAUCE block populated from the active BBS. Consumes the File’s write consent. Returns null on success or a FileError on write failure.

Mouse state

mouseMode (effective native protocol: 0 = off, 1 = RIP, 2 = SkyPix, 3 = IGS, 4 = BIG pointer, 9 = X10, 1000/1002/1003 = the tracking modes), mouseSgrPixels (Bool — true when DECSET 1016 SGR pixel-position reporting is active), mouseDisabled / mouseDisabled = b (Bool — disables forwarding local mouse events to the remote tracking protocol)

Throttle

throttleSpeed (live network character-pacing rate, BPS; 0 = unthrottled), throttleSpeedUp() / throttleSpeedDown() (walk the rates ladder; no-op on serial)

Bitfield snapshots

extAttr (ExtAttr), lastColumnFlag (LastColumnFlag)

CTerm.font[i] is a live, writable view of terminal font assignments. Indices 0 through 9 correspond to SGR 10 through 19. All ten start with the configured default font. In the primary rendition, positions 0 through 3 also supply the normal, source-bright, source-blink, and bright-plus-blink fonts. Reading returns a selector; writing changes only that assignment. This is independent of the five Screen.font slots for script drawing.

CTerm.setFont(selector, mask) changes all requested assignments together. CTermFontMask.normal is 1, .bright is 2, .blink is 4, .brightBlink is 8, and .all is 1023. Use 1 << i for an individual position. Combine bits with |; zero and unknown bits are invalid. Selection requires an available registration and a capable backend. It finishes pending output before committing; failed selection leaves every assignment unchanged. Existing cells retain their resolved fonts. Selection does not change the video flags which enable source-bright/blink font selection.

The method returns null on success or FontError on an operational failure. An indexed write raises that same FontError through ordinary Fiber abort, so failed assignment statements cannot silently discard a returned error. Assignment expressions can capture setter results in standard Wren; this particular indexed setter deliberately aborts on failure. Catch it with a Fiber’s .try() when recovery is needed. The terminal assignment interface is connected-VM-only. The old CTerm.altFont and detached CTerm.altFonts List are removed without aliases. The shipped picker still changes only the normal assignment when selecting an existing font; loading only registers a new font.

Action Description

CTerm.write(s)

Render strict UTF-8/NFC text directly through the native semantic-input path, independently of the wire encoding. Returns null on native success or CTermError on native failure. Valid NUL and other controls retain their terminal meanings. Input filters are bypassed as before; native capture and incremental parser/decoder behavior are unchanged. Local render success does not promise delivery of any protocol-generated network reply.

CTerm.sendKey(event)

Forward a KeyEvent or PhysicalKeyEvent through the current terminal’s native keyboard path, preserving the source type and modifiers. Returns Bool on native success or CTermError on native failure. The Bool reports acceptance, including local-only actions and queuing behind suspended RIP3 drawing. Immediate dispatch returns false for unsupported mappings. An active native WireLease also returns false. Check for Error before interpreting the Bool. Error values are truthy. Invalid arguments abort. Forwarded keys enter the same graphics and emulation path as keys passed by input hooks, in order, without re-entering the hooks. For example, CTerm.sendKey(KeyEvent.new(Key.enter)) forwards Return.

CTerm.keyboardLocked

Bool. Reports whether the active RIP3 or DDO F/X scene has locked keyboard input. A shortcut that submits terminal data directly can check this before sending.

CTerm.setThievesGuild(enabled), CTerm.thievesGuild

Enable or disable the Thieves' Guild front end for the current Atari ST session. Pass a Bool. The method returns null on success or a CTermError. The getter reports whether detection is enabled, including while waiting for the door’s startup banner. The Online Menu uses this same setting.

CTerm.startMusicomm(), CTerm.musicomm

Locally arm the Musicomm receiver and read whether it still owns received bytes (including startup/end drains). Start returns null on success or CTermError on failure, including Busy while another receiver owns the connection. A missing session aborts. It finishes pending terminal output and replaces channel-0 music. The sender must handshake with byte 02 and pace note toggles in real time; no terminal escape sequence activates it. An available configured MIDI destination takes precedence over the Atari ST speaker fallback. A key passed by the connected input hooks or forwarded by CTerm.sendKey aborts playback and is consumed. Reset/EOF/destruction cancel it. See docs/MUSICOMM.md for protocol, guard intervals and coverage.

CTerm.reset()

Invoke the direct native terminal reset synchronously. Returns null on native success or CTermError with the exact native failure code. Requires the connected VM’s assigned terminal, independently of whether the network is still connected. Menu/picker and missing-terminal calls abort without invoking reset. + The native operation finishes pending input, resets parser/mode and cursor settings, and rebuilds enabled RIP state, including reloading its persisted variables. Finishing a buffered RIP command can invoke its existing host prompt or other callback before reset proceeds. This is distinct from feeding a reset escape sequence through CTerm.write. The binding adds no screen/history clear, resize, encoding change, reconnect, wire claim or suspension change. Existing native generated-response suppression under WireLease/transfer ownership remains in force; local reset does not create a new busy/network failure policy. + Failure may follow pending-output processing or partial reset, including a partially rebuilt RIP engine. It provides no rollback or automatic retry and does not guarantee that the terminal remains usable. The operation retains no arguments or native resources.

CTerm.suspended, CTerm.suspended = b

Read or write the wire-pump suspend flag. When set true, the main loop stops draining bytes from the conn buffer. Bytes pile up in the conn buffer; the TCP receive window eventually fills and the remote sees its send() calls block or EAGAIN. Use this to claim the screen for a modal dialog, transfer overlay, etc., without remote output painting underneath. Clear it again when you’re done. Pushing an Input.pushClaim does not suspend on its own — scripts that want modal behavior must set this explicitly. When speed emulation is active and the flag transitions from true back to false, the byte pump is credited with all the bytes that would have processed at the emulated rate during the suspended interval; those bytes drain past the speed gate as fast as the pump can run, so the visible output catches up to where it would have been if the suspend had never happened.

CTerm.mouseDisabled, CTerm.mouseDisabled = b

Read or toggle the session gate for forwarding mouse events to the remote tracking protocol. Changes take effect immediately; local UI subscriptions remain controlled by Input.mouseEvents.

CTerm.mouseMode

Read-only effective native mouse protocol: 0 (off), 1 (RIP), 2 (SkyPix), 3 (IGS), 4 (BIG pointer), 9 (X10), 1000/1002/1003 (the XTerm tracking modes). RIPv3 reports 1 while its separate engine owns mouse fields. The default drag hook then leaves those gestures to the engine. Used by the default status bar to light the "M" indicator. SkyPix is available without a host enable command; Alt/Command-O or Toggle Remote Mouse in the online menu controls mouseDisabled. A disabled indicator remains visible but dim. SkyPix sends ESC[21;1;x;y! on left-button down in native zero-based canvas pixels, with no trailing newline. Releases, other buttons, movement, status-row and UI-handled events do not report. Cell-only events without native pixel coordinates are not approximated. Wheel-up retains the local scrollback action. IGS reports mode 3 while X3 or X6 is enabled/holding input, or an interactive ? query or < zone collection owns the mouse. Those clicks are consumed by the active acquisition and do not trigger outer X3/X6. X3 sends the loaded raw macro once on right-only, optionally followed by CR, then waits for all buttons to release. X6 waits for a left-only hold to change to any other button state before sending CR; only mode byte2 adds LF. A transition to right-only can then enter X3. Serial input and queued keys resume after these holds. Status-row and UI-handled presses do not activate either behavior; release is accepted anywhere. IGS keeps wheel-up local for scrollback.

BIG reports mode 4 while < pointer acquisition is active. Keyboard steps and native mouse movement share its software pointer; stationary button samples preserve the keyboard position. Left-button release after a valid press confirms the current point. UI-handled/disabled/outside samples disarm selection; wheel-up remains local. BIG’s selected zone data follows its deferred counted-reply path, not an ANSI mouse report.

CTerm.mouseSgrPixels

Read-only Bool; true while DECSET 1016 is the active SGR pixel-position reporting mode. False for IGS, SkyPix and an active BIG pointer. SkyPix controller reports use their own pixel-coordinate format even if an ANSI mouse mode was requested.

CTerm.doorwayMode, CTerm.doorwayMode = b

Read or write the cterm doorway-mode flag. When true, the input pump passes most keys through verbatim instead of decoding them; used by door programs that want raw scancodes.

CTerm.ooiiMode, CTerm.ooiiMode = n

Read or write the Operation Overkill ][ terminal mode (0 = off, 1..Host.maxOOIIMode = the OOTerm modes). Setting out-of-range integer values is clamped. Changing modes discards a partial protocol command. Embedded sound effects use the terminal’s shared SFX stream and lazy audio runtime.

CTerm.throttleSpeed, CTerm.throttleSpeed = bps

Current network character-pacing rate in BPS. 0 = unthrottled (no per-byte sleep). Always 0 on serial connections; the configured port speed lives in Session.current.profile.bpsRate. Default status bar reads this to render the live rate; the online_menu Output Rate picker writes via the setter.

CTerm.throttleSpeedUp(), CTerm.throttleSpeedDown()

Walk throttleSpeed one step up or down the BBS-list rates ladder (300, 600, 1200, 2400, 4800, 9600, 19200, 38400, 57600, 76800, 115200). Up from 0 jumps to 300; Down from 300 drops to 0 (unthrottled). No-op on serial connections. Default keys script binds these to Key.up / Key.down with Mod.command.

CTermError

An immutable Error returned by write, sendKey and reset above. There is no public constructor. It owns scalar diagnostics and message storage, retains no input String, terminal or session, and remains usable through later calls and GC within its VM.

Member Description

code

Exact native I/O integer, comparable to IOErr constants. Unknown integers are preserved; success uses the operation’s normal null/Bool value.

message

Nonempty human-readable operation/reason diagnostic.

consumedBytes

Write errors only: native consumed count in the normalized UTF-8 input; null for key/reset errors. This is not a rendered-character count or a safe retry offset into the original Wren String. A failure may consume all input, or stop within a multibyte sequence, and parser/decoder effects remain.

handled

Key errors only: the native acceptance Bool, including local-only actions; null for write/reset errors. It does not confirm transmission or safe retry.

toString

Includes CTermError, code and message for display, not parsing.

Wrong types, invalid event objects, malformed UTF-8 and missing required native terminal/session state remain programmer errors raised through ordinary Fiber abort. An impossible native consumed count, or native success with incomplete consumption, also aborts as a native contract violation; no I/O status is invented. Native output policy is unchanged: key errors can reflect retained output failures, and disconnect suppression permits auxiliary work to continue. These values provide no rollback, automatic retry or network-delivery guarantee.

var result = CTerm.sendKey(KeyEvent.new(Key.enter))
if (result is CTermError) Fiber.abort(result)
// result is now the native acceptance Bool.

ExtAttr

Snapshot of cterm’s extended-attribute bitfield. All members are read-only Booleans reflecting the corresponding terminal mode.

Member Description

autoWrap

DECAWM — characters past the right margin wrap to the next line.

insertMode

IRM — graphic characters shift text to the right when inserted.

originMode

DECOM — cursor coordinates are relative to the active scroll region rather than the screen.

sxScroll

SIXEL scroll: when a SIXEL image extends past the bottom of the screen, scroll the screen up to make room. When clear, the image is clipped at the bottom row.

decLrmm

DECLRMM — left/right margin mode enables horizontal scroll regions.

bracketPaste

DEC mode 2004 — pasted text is bracketed by ESC[200~ / ESC[201~ markers.

decBkm

DECBKM — Backarrow key sends BS (0x08) instead of DEL (0x7F).

prestelMosaic

Prestel mosaic graphics character set is active.

prestelDoubleHeight

Current row is rendered double-height.

prestelConceal

Concealed (hidden) text mode.

prestelSeparated

Separated mosaics — gaps between mosaic blocks.

prestelHold

Hold-graphics mode — control codes render as the most recently emitted mosaic glyph rather than blanking.

alternateKeypad

DECKPAM — numeric keypad sends application keypad codes instead of digits.

LastColumnFlag

Snapshot of cterm’s last-column-flag state. Used by emulations that distinguish "cursor at the right margin" from "cursor wrapped to next line" (the so-called phantom-column).

Member Description

set

Bool — the flag is currently set: the cursor sits at the right margin awaiting the next character to wrap it. Cleared by any cursor-positioning sequence.

enabled

Bool — last-column-flag tracking is enabled at all. Some emulations disable it.

forced

Bool — tracking is forced on regardless of the underlying mode (set by SyncTERM’s emulation-bridge code or the BBS list’s forceLcf flag).

StatusDisplay

Referenced by CTerm.statusDisplay. VT320 DECSSDT (Select Status Display Type) values: which status line, if any, the bottom row is acting as.

Constant Code Description

none

0

No status line — the bottom row is part of the main display area.

indicator

1

Indicator status line — terminal-managed diagnostic line (e.g. "INSERT", connection state). The host can’t write to it.

host

2

Host-writable status line — the bottom row is a separate addressable region the BBS can direct writes to via DECSASD.

Profiles

Profile in syncterm is the shared connection-configuration contract in all VMs. DirectoryEntry.profile and Menu.defaults are views into the working menu model. Session.current.profile is a cached, read-only snapshot of the configuration captured for this connection. profile.copy() returns an independently owned editable value, without a directory identity or statistics. Quick-connect configurations are independently owned values too; later quick connections and menu reloads do not overwrite or invalidate them.

readOnly identifies system/web views and session snapshots. Their setters abort. All other Profile fields below have getters and setters, except the derived display string connTypeName. Profiles have no rename/save/delete, entry IDs, statistics, or cache authority. Use Menu.copy(profile, name) to create an entry; selecting a Profile starts a transient connection without updating another entry’s statistics.

Group Fields

Address

addr, port, connType (ConnType), connTypeName (display string for connType), webSocketTarget, comment

Network

addressFamily (AddressFamily)

Auth

user, password, syspass, sftpPublicKey, sshFingerprint, sshAllowAes128Cbc, sshAcceptEarlyData, tlsTrustWebPki, tlsTrustedCert, tlsClientCert, tlsClientKey, tlsPskIdentity, tlsPsk, tlsPskVersion, tlsVersionFloor, ghostProgram

Presentation

music, graphics, termName, screenMode, customScreenMode, font, amigaFont, amigaFontSize, encoding, palette, noStatus, hidePopups, yellowIsYellow, forceLcf, lfExpand

Files and logging

dlDir, ulDir, logFile, appendLogFile, xferLogLevel, protocolLogLevel, ctermLogLevel

Serial and protocol

bpsRate, stopBits, dataBits, parity, flowControl, telnetNoBinary, deferTelnetNegotiation

Scripts

wrenScripts, the ordered List of entry-selected connection modules. Defaults expose an empty List and reject assignments.

Connection strings, credentials, paths, and comments use the normal strict UTF-8/NFC text boundary without NUL, with field-specific size limits. tlsPsk is literal text, without hexadecimal or Base64 decoding. sshFingerprint is an exact byte String of length 0, 20 or 32; use .bytes.count for its length. palette and wrenScripts return fresh Lists; their lengths replace the old redundant size getters. Invalid assignments leave existing values intact.

profile.customScreenMode returns null when Custom follows Program Settings, or a fresh List in the order [columns, rows, fontHeight, aspectWidth, aspectHeight]. Assign a complete List to store an override, or null to clear it. Columns and rows accept integers from 1 through 255, font height from 1 through 64, and each aspect component from 1 through INT_MAX. The matching optional BBS-list key uses comma-separated integers, for example CustomScreenMode=96,32,8,3,1. An incomplete or malformed tuple inherits the program mode. A saved profile retains its override when another screen mode is selected.

Configured profile.encoding uses the profile encoding catalog and remains unchanged when terminal decoding changes. CTerm.encoding reports the live TerminalEncoding.utf8 (0) or TerminalEncoding.codepage (1); CTerm.codepage reports the live Codepage value. Session.current.name, entryId, entrySource, added, lastConnected and calls describe the session’s captured identity and connection statistics. Conn.elapsedSeconds is live elapsed time. The former BBS classes and static namespace are removed.

The menu VM imports Menu, DirectoryEntry, and MenuError from syncterm_menu. Menu owns a C-side transactional view of the personal, installed system, and web-cache BBS lists. It is not available in a connected VM.

Method Description

Menu.load(password)

Load all lists and replace the current model only after the complete load succeeds. password is a String or null. Returns null on success or MenuError preserving the portable native reason in code and nativeCode. The message identifies loading, sorting, or model construction. Any failure leaves the current model, generation, views, grants and diagnostics unchanged. Password prompting uses IOErr.passwordRequired and IOErr.decryptionFailed.

Menu.loadDiagnostics

Return a fresh List of immutable BBSLoadDiagnostic snapshots from the current installed list, in native order; empty without a loaded model. Reading does not reload files or change the model. See BBS load diagnostics.

Menu.quickConnect(url)

Parse a String using SyncTERM’s normal URL rules and return an owned editable Profile, or null for an unusable address. It remains valid across further quick connections and reloads. It can be returned from MainMenu.run; use Menu.copy(profile, name) to create a directory entry. The ws+telnet:// and wss+telnet:// schemes populate Profile.webSocketTarget with the absolute HTTP path and optional query, preserving percent escapes. Set it to an empty String to select /. The target contains neither the scheme nor the host.

Menu.offlineScrollback

Return a detached Surface copy of the most recently completed session’s linear scrollback, or null when none exists. The copy is safe to retain across later connections; it does not borrow the process buffer which the next session may resize or replace. Optional graphic row strips retain their captured colours and both blink planes. A pixel-copy failure returns ScreenError.

Menu.offlineScrollbackHeight

Number of rows in the most recently completed session, including its saved terminal page, subject to the configured capacity.

Menu.offlineScrollbackRow(index), Menu.offlineScrollbackGeometry(index)

Read one detached row or its original geometry, using the same coordinates and return types as Scrollback.row and Scrollback.rowGeometry. Menu.offlineScrollback supplies the rectangular projection at the final width.

Menu.prepareOfflineScrollback()

Select the completed session’s text mode, restore its mode-specific fonts and palette, and draw the terminal background. Returns false when no scrollback exists, true on preparation success, or ScreenError on an operational failure. This changes global console state. Save the screen first, then call finishOfflineScrollback() before restoring that screen, including on errors or cancellation.

Menu.finishOfflineScrollback()

Restore the original menu geometry after preparing detached history; returns null or ScreenError. It is idempotent and leaves an enclosing disconnected session’s mode bracket intact. The shipped viewer pairs this with preparation through its cleanup scope.

Menu.offlineScrollbackHasStatus

Return whether the completed session’s terminal layout reserves a status row. The shipped viewer uses the full screen height for Page Up/Page Down and this value to recover the terminal height used by H/L.

Menu.openUrl(url)

Open a detected plain-text URL with the configured local URL handler. Returns whether it opened, or ScreenError for an operational failure. This menu-only operation carries local browser authority, is unavailable to connected scripts, and returns false in safe mode.

Menu.openHyperlink(id)

Resolve an ID from the shared hyperlink registry and open HTTP, HTTPS, FTP, or FTPS URIs with the configured local URL handler. Scheme matching is locale-independent and case-insensitive. Returns false for other schemes, unknown IDs and safe mode; launch failures return ScreenError. The shipped viewer copies the URI to the clipboard when opening fails.

Menu.setHyperlinkHover(id)

Select the link pointer when id names a registered hyperlink, or the text pointer otherwise. The shipped offline viewer separately resolves and paints the full URI in its bottom row; pass zero to clear hover state. Returns null or ScreenError. Text-only and libretro backends do not expose pointer shapes; bundled callers skip this optional chrome when unsupported.

Menu.applicationTitle

Return the classic header text, combining the SyncTERM version and active conio output-backend description. This is display data and does not change the OS window title.

Menu.timeText

Return the current local time in the classic 24-character Fri Jul 17 2026 07:30 pm form used by the offline title row.

Menu.timestamp

Return the current Unix timestamp as a Num. Trusted offline applications can use it to initialize date-oriented widgets without a connected Session or Conn clock.

Menu.showEntry(entry)

Set the OS window title to the classic name/call-count/last-connected summary for a current DirectoryEntry or Profile. Passing null restores the bare SyncTERM version title. The purpose-specific operation returns null or ScreenError; stale views and values of unrelated classes abort. It is menu-only so connected scripts do not gain arbitrary application-title authority.

Menu.quitApplication()

Set SyncTERM’s process exit latch after trusted menu code has completed any required work. This is available for explicit menu commands; OS window-close requests set the same latch in the host.

Menu.entries

Return a new List of host-created DirectoryEntry views in current sort order. The records themselves remain C-owned.

Menu.canAppendEntry

Return whether the combined personal and read-only directory has room for another personal entry.

Menu.scriptModules

Return a fresh List of valid root script-module names available for per-entry connected loading. The list is rebuilt from user scripts/*.wren files in case-sensitive byte order; embedded modules, invalid names, and the reserved menu and picker module names are omitted. The entry editor separately omits names already selected.

Menu.wrenScriptsMaxLength

Maximum byte length of the comma-separated WrenScripts INI value. The shipped editor omits additions which would exceed it.

Menu.defaults

Return the mutable defaults Profile view, or null before loading. Scripts are configured per entry: root-section WrenScripts is ignored, defaults expose an empty script list, and assigning scripts to defaults aborts. The defaults editor omits scripts. New entries start without scripts; entries without their own WrenScripts stay empty when edited.

Menu.defaultsDirty

Bool indicating unsaved default configuration changes.

Menu.saveDefaults()

Persist the working defaults to the root section. Returns null/MenuError; safe mode returns IOErr.readOnly. Profiles have no persistence methods.

Menu.nameAvailable(name)

Test whether a new personal entry name is valid and unused by another personal entry. Names are 1..30 Unicode scalars and at most 60 UTF-8 bytes; identity uses Unicode canonical caseless matching. The reserved syncterm-system-cache name is rejected. A personal entry may intentionally shadow a read-only system entry of the same name.

Menu.create(name)

Create an unsaved personal entry from Menu.defaults, reset its statistics, insert it into the sorted working model, and return its DirectoryEntry or MenuError for an invalid/duplicate name or allocation failure.

Menu.copy(source, name)

Create an unsaved personal copy of source, with reset statistics and the supplied name, and insert it into the sorted working model. source may be a current DirectoryEntry or a Profile, including defaults, detached copies and quick-connect values. Returns DirectoryEntry/MenuError.

Menu.sort()

Reapply the configured BBS-list sort profiles. Returns null/MenuError.

Menu.sortFields

Return fresh [fieldId, displayName, defaultReversed] rows from the host sort-field registry. Field IDs are positive. The Boolean says that the field’s normal profile direction is descending. Encoding is field 32, ordered by canonical encoding number (UTF-8 is 255); -32 reverses it. Existing field IDs and persisted aliases are unchanged.

Menu.sortProfiles

Return fresh [name, order] rows. order is a List of unique signed field IDs and may be empty; negating an ID toggles that field relative to its defaultReversed direction.

Menu.activeSortProfile

Zero-based index of the active profile.

Menu.setActiveSortProfile(index)

Select a profile in memory, apply its order, and re-sort the loaded directory. Returns null/MenuError; invalid indices abort before the native call.

Menu.addSortProfile(index, name, order)

Insert a profile. Names are 1..19 Unicode scalars, at most 38 UTF-8 bytes, and canonically caseless-unique. They cannot contain controls, leading or trailing Unicode whitespace, =/:, and cannot begin with ; or [. Returns null/MenuError; invalid arguments and duplicate names abort.

Menu.updateSortProfile(index, name, order)

Replace a profile’s name and field order. Updating the active profile also re-sorts the loaded directory. Returns null/MenuError; invalid arguments and duplicate names abort.

Menu.deleteSortProfile(index)

Delete a profile and re-sort with the resulting active profile. Deleting the last profile restores the built-in profiles. Returns null/MenuError.

Menu.saveSortProfiles()

Write the working profiles, active profile, and current order to syncterm.ini. Returns null/MenuError. Safe mode returns IOErr.readOnly.

The shipped offline viewer saves the menu screen, calls prepareOfflineScrollback(), captures the resulting background, and restores the saved mode, fonts, palette, video flags, cursor, mouse subscriptions, and screen when it closes. It starts at the newest screen. Up/J and Down/K move one line, Page Up/Page Down move by the physical screen height, H/L move by the terminal content height, the mouse wheel moves one line, F1 opens the Markdown help, and Escape returns to the directory. Clicking opens OSC 8 or detected plain-text URLs, hovering shows an OSC 8 URL in the status row, and button-one drag copies text in reading order. Alt at button press selects a rectangle. In mixed geometry the viewer shows the hovered URL in its title row. Horizontal arrows pan, and holding a dragged pointer at the viewport edge continues scrolling. Both selection modes use each row’s original columns.

In v2, MenuReadStatus and Menu.statusMessage are removed without aliases, including obsolete migration status values. Successful loads can still contain warnings about skipped sources or sections, or truncated entry names. The bundled menu opens a scrollable Directory Warnings summary when any warning comes from a personal or shared list. Up/Down scroll one line, PgUp/PgDown scroll a page, and Home/End jump to the top/bottom. Enter continues and Escape closes the dialog. Once dismissed, an unchanged warning summary does not reopen during subsequent loads in the same menu VM, including returns after disconnect. A changed summary can reopen it; a successful load without an automatic warning clears the remembered summary. Warnings remain available through Menu.loadDiagnostics on every load. Warnings exclusively from web lists do not open the dialog automatically, but remain in the diagnostics and appear alongside other warnings when the dialog opens. Dismissal continues with usable entries; missing optional files remain silent. A diagnostic retrieval failure still opens the dialog every time as warnings unavailable, without treating the successful load as failed. Password cancellation and fatal load errors retain their existing prompts and error dialogs, even when all retained warnings are from web lists. There are no automatic retries.

A DirectoryEntry owns name, searchKey, source, sourceName, shadowed, id, added, connected (persisted LastConnected timestamp), lastCallText, calls, readOnly, dirty, profile and cache. Only sortOrder has a property setter. rename(name), save() and delete() return null/MenuError; toString returns its name. id survives sorting, rename, save and unrelated model edits. An unsaved draft has -1 until its first successful save. IDs are local to a load and are not serialized. Native ownership also distinguishes replaced records independently of their names, addresses or numeric IDs.

lastCallText formats the persisted last-connected timestamp as a local-time YYYY-MM-DD date, Never for zero, or Unknown if it cannot be represented. It performs no I/O and follows the entry handle’s ordinary lifetime.

source preserves the native list source using BBSListSource.personal (0), shared (1), webSystem (2), or webNamed (3). sourceName returns null for personal entries, the shared-list path, "System List" for the system web list, or the configured named web-list name. Source names are validated as UTF-8 and normalized to NFC on access. A conversion failure returns MenuError with the actual status in code and nativeCode; it does not change the loaded model. Reading other fields does not construct a source-name String or Profile snapshot. New and copied personal entries have personal provenance and no source name.

shadowed returns a read-only DirectoryEntry view of the next lower-priority record retained by the native or working directory model, or null. Traverse only the records actually retained; this does not enumerate every list containing that name or change native precedence. Its profile is a read-only view, cache is null, setters abort and rename/save/delete return read-only MenuError. Explicit Menu.copy() and profile.copy() use the ordinary copy rules. The view creates no file authority and remains excluded from Menu.entries.

Hidden entry/profile views follow normal directory lifetimes: sorting and unrelated edits preserve them, a successful load replaces them, and a failed load preserves them. Restoring a hidden record to the visible list invalidates its old hidden view; an old visible view does not revive when that record is restored. Captured Strings and detached Profile copies remain independent.

The former directory classification getter entry.type is removed. It now inherits Wren’s standard Object.type, returning the DirectoryEntry class. Use entry.source for provenance and entry.readOnly for editability. BBSListType and Session.entrySource still represent the native profile’s separate personal/system classification; no Profile.source getter is exposed.

searchKey retains the NFD full-default-casefold form of the name. The shipped list uses it as a cheap search prefilter and verifies grapheme boundaries. Configuration lives on entry.profile; its setters share the working record and mark the entry dirty. Saving persists those edits and an in-memory rename together. Deleting a persisted entry updates disk before removing the record; deleting an unsaved draft only discards that draft. System/web views reject configuration setters; rename/save/delete return MenuError with IOErr.readOnly. Menu.copy produces a personal editable entry. Safe mode permits working edits but rejects persistence.

entry.cache is a Directory for a saved personal entry, created through the normal cache resolver. It returns null for unsaved/system/web entries and a FileError on native failure. Before a pending rename is saved it refers to the persisted name’s cache. Saving the rename uses the native cache move policy. Previously issued cache grants and their descendants become stale at that point, on removal/replacement, and on reload. They cannot access a later entry at the same name/path. An already open File retains its stream and can always be closed; path-based operations still require a current grant. Displayed paths confer no new authority. This adds no arbitrary filesystem constructor.

The shipped entry editor invokes those setters, including rename(), after each nested field editor accepts a changed value. It calls save() for a dirty entry when the entry editor closes. The Wren Scripts editor applies additions, deletions, and completed moves to the working Profile immediately; save() writes them as the comma-separated WrenScripts value in that entry’s INI section. The fingerprint has no direct editor row; the shipped F5/F6 clipboard carries it through the draft so copying an entry preserves an accepted SSH host key.

TLS certificate/key and PSK identity/secret pairs can be edited one field at a time. The editor validates complete pairs before saving and remains open when a pair is incomplete. C-backed text fields also enforce their UTF-8 byte limits before invoking a setter.

Download Path and Upload Path remain direct entry rows. Log Configuration opens Log Filename, File Transfer Log Level, Protocol Log Level, CTerm Log Level, and Append Log File. Accepted values still update the working Profile before the logging submenu closes.

The persisted INI name is ProtocolLogLevel. During the pre-release rename, a missing ProtocolLogLevel falls back to the legacy TelnetLogLevel value; saving the entry writes the new name and removes the old one. When neither global key exists, the default protocol log level is Error.

CTermLogLevel is saved independently for each entry and connection default; its default is Error. CTerm diagnostics share the configured LogFile and append setting, with a CTerm source prefix. Warning includes detected unsupported or invalid sequences, rejected parameters, and malformed UTF-8. Debug also reports final missing grapheme clusters (.noglyph) with their Unicode code points, selected console font identifier, and screen position. An exact match supplied by compatible font zero is not a missing glyph.

A successful full load invalidates entry/default views and cache grants from the replaced model. A failed load preserves them. Creating/deleting unrelated entries, sorting and saving preserve existing identities. Deleted or shadowed entries become stale; restoring a shadowed system record does not revive an old view of it. Detached Profile values and session snapshots remain valid.

BBS load diagnostics

Menu.loadDiagnostics creates snapshots only when requested. BBSLoadDiagnostic is menu-only, host-created, and immutable, with no public constructor or setters:

Property Description

source

BBSListSource.personal (0), shared (1), webSystem (2), or webNamed (3), preserving native source values. This is distinct from BBSListType.

sourceName

Nullable source identifier: null for the personal list, the shared list path, "System List", or the configured named web-list name.

sectionName

The original section name for a skipped or truncated entry, or null for a source-level failure.

error

A fresh MenuError with the native portable diagnostic status in both code and nativeCode, and a readable reason. Constructed only on access.

Snapshots own their names and scalar data, survive reloads and garbage collection, and retain no borrowed list pointers, secrets or filesystem authority. Their names are strict UTF-8/NFC host text. Allocation or text-conversion failures raise MenuError through ordinary Fiber abort; they do not alter the loaded model. The returned List is independently mutable; its records are immutable. Diagnostics come from the installed native list, including its existing rebuild behavior, not from a failed replacement candidate. Entry provenance and shadowed records are separate from these warnings.

Overlong entry names are loaded using the longest valid prefix within 30 Unicode scalars and 60 UTF-8 bytes, preserving complete UTF-8 scalars and removing trailing whitespace at the cutoff. Their diagnostic has IOErr.nameTooLong and retains the full original section name. Values are read from that original section; the shortened name determines entry identity and the usual duplicate/priority rules. Editing or deleting a personal entry still addresses its original section. Malformed or otherwise invalid names retain the existing rejection policy.

import "syncterm_menu" for Menu

var failure = Menu.load(null)
if (failure != null) {
  System.print(failure.message)
} else {
  for (item in Menu.loadDiagnostics) {
    System.print("%(item.sourceName): %(item.error.message)")
  }
}

In v2, BBS and Settings mutation actions return null on success or a host-created, immutable MenuError. Creators (Menu.create, copy, createFromProfile, createFont) return their object or MenuError. This covers entry rename/save/delete, defaults/encryption/sort, Settings apply/save/reload, font/web/sort collection actions, Menu.load, and theme operations described below. Predicates retain their own contracts. There are no Boolean compatibility forms.

Member Description

code

Portable IOErr reason, or null when the called C API supplies no portable reason. Classify by the API’s contract, never by the raw integer alone.

nativeCode

Actual integer C failure, or null for Boolean/pointer failures and host-only policy rejection. ThemeDocument.save retains its separate native ThemeSaveErr enum here with code null. Generic -1 from older collection APIs is retained here with code null; it is not classified as IOErr.invalidArgument.

message

Owned operation-specific diagnostic; portable failures include their reason.

toString

Diagnostic prefixed by `MenuError: `.

MenuError has no public constructor or setters, retains no borrowed native data, secrets or resource authority, and remains usable after reloads and collection. It is available only in the trusted menu VM and inherits the ordinary Error base. Existing invalid-argument and stale-handle aborts remain. Native mutation failures in property setters raise MenuError through ordinary Fiber abort.

Native C APIs, call order and partial effects are preserved. A list KDF rewrite may succeed before a Settings save fails. Collection edits may precede a later native failure, and installed settings may precede a runtime application failure. Messages identify completed earlier steps where known. Once settings are installed, generation/dirty transitions still occur even if applying a runtime option fails. There is no rollback or transaction-state API. Inspect current models as needed; no automatic retry is performed. Optional cache housekeeping remains outside primary BBS mutation success. Safe-mode blocked operations return IOErr.readOnly, including saveSortProfiles, which formerly reported a successful no-op.

var error = entry.save()
if (error != null) System.print(error.message)

The Retro editors use the existing Profile.copy() to keep profile changes out of the working directory until Save. The following menu-only additions accept an owned, editable, detached Profile; passing another foreign type or a borrowed profile view aborts. They do not consume the supplied Profile.

Operation Result and behavior

entry.saveDraft(profile, name, sortOrder)

Update an existing personal entry and persist it, returning null/MenuError. Preserve entry identity, provenance, call statistics, and other entries. name follows the existing entry-name rules and sortOrder is a signed 32-bit integer. Stale receivers abort; read-only targets return IOErr.readOnly.

Menu.createFromProfile(name, profile, sortOrder)

Persist a new personal entry and return its DirectoryEntry or MenuError. Reset call statistics using the same rules as Menu.copy; normal name, capacity, and shadowing rules apply. A failed creation leaves no unsaved entry.

Menu.saveDefaults(profile)

Persist replacement new-connection defaults, returning null/MenuError. The existing zero-argument overload still saves the mutable working defaults.

Preparation and persistence are serialized on the menu thread. No application callback observes a partially prepared record. Failure restores the working record and preserves its views; success publishes the replacement and reapplies sorting. Existing native write-error and secondary-cache semantics remain: a failed write can partially modify the file, and cache maintenance is separate from primary mutation success. These operations do not create a general-purpose transaction or filesystem rollback facility. Safe mode returns IOErr.readOnly.

Menu.settings returns a C-owned Settings snapshot. Property setters validate the assigned value, change only that snapshot, and set dirty. apply() applies the snapshot to the running program without writing syncterm.ini. Values copied from the running settings are not revalidated, so values accepted by older versions pass through unchanged. reload() discards changes not yet applied and repopulates the same handle from the current running settings. It does not reread syncterm.ini, including when another process has edited that file. The native raw global reload is intentionally not exposed: it replaces configuration data and the merge baseline without coordinating runtime fonts, themes, audio or layout. There is no full application disk-reload method.

dirty specifically means that the snapshot differs from the running settings. A successful apply() clears it. It does not indicate whether those running settings have subsequently been written to syncterm.ini; code which separates apply() from save() must track that persistence obligation itself.

save() preserves unrelated INI sections, writes the existing syncterm.ini keys, and applies the settings which have immediate effects. These include scrollback capacity, scaling, mouse-wheel direction, audio backends, custom-mode dimensions, cursor style, and the Classic Theme colours used when the built-in theme is active. It returns MenuError when preparation, encrypted-list rewriting, INI persistence, or runtime application fails; success is null. A failure before installation does not apply an unapplied snapshot; settings already accepted through apply() remain active. Changing the KDF work factor may rewrite an encrypted BBS list during apply(). Saving syncterm.ini is disabled in safe mode: save() returns MenuError with IOErr.readOnly before applying the snapshot, and the snapshot remains dirty.

The allowed audio-backend mask changes immediately. Backend selection occurs when the process first opens its audio engine; changing an already-open backend requires restarting SyncTERM. Startup screen and video output preferences also take effect on the next startup. In safe mode, applying a KDF change which would rewrite an encrypted directory returns IOErr.readOnly without changing the directory or installed settings.

Installing a snapshot during apply() or save() advances the settings generation, even if a later runtime application step fails. The object which performed the operation remains valid and clean, but any other outstanding Settings handles become stale and abort when used. Reacquire a snapshot from Menu.settings after another component applies or saves settings.

The Classic Program Settings editor calls apply() after each accepted setting and calls save() once when the editor closes. Thus settings with immediate effects change at field-confirmation time while the INI write remains grouped at the Program Settings screen-exit boundary. If the write fails, the screen remains open so saving can be retried.

promptSave controls the save offer for a temporary URL connection when the application exits. The offer is suppressed in safe mode, when that entry has hidePopups set, and for entries already saved in the directory.

The Classic editor keeps Classic Theme Colours and Custom Screen Mode as nested groups instead of flattening their fields into Program Settings. A connected invocation omits Custom Screen Mode. The connected settings list also omits Current Screen Mode and List Encryption; List Encryption is omitted in every mode when Menu.encryptionAvailable is false.

Property Meaning

atariStKeyClicks

Bool, defaults to true. Enables local Atari ST keyboard clicks independently of the terminal bell and remote sound effects. The Program Settings row toggles on selection and applies immediately, including during a connection. Persists as AtariSTKeyClicks under [SyncTERM].

mainUi

Built-in main interface: 0 is Classic (default), 1 is Retro. Other assignments abort. Menu.mainUiChoices supplies [value, label] rows. This uses the normal settings snapshot, apply/save, merge, generation, and safe-mode contracts. The built-in controller changes presentation after Program Settings returns.

confirmClose, promptSave, invertWheel, colorEmoji

Bool program options. colorEmoji defaults to true and enables intrinsic emoji colours in graphical output. Disabling it uses monochrome artwork without changing sequence matching or cell widths.

modemDevice, modemInit, modemDial, shellTerm

Modem strings and the terminal name exported to local shell connections. The shipped editor accepts 1024 bytes for the device, 1023 bytes for either modem command, and 30 bytes for shellTerm, matching the intended controls and their backing fields.

listPath

Stored personal-list path or URI. The host resolves it to the active local or cached list path after a successful apply or save. The shipped editor limits it to Menu.maxPathLength.

startupMode, outputMode, cursorStyle, audioModes, midiModes, scalingMode

Catalog-backed display, backend, and audio selections. audioModes is a bit field, so the values in Menu.audioModes may be combined. midiModes independently enables MIDI methods from Menu.midiModes and persists as MidiModes under [SyncTERM]; zero disables MIDI. Its default is all bits enabled. Both masks accept 0 through UINT32_MAX.

openGLPreset

OpenGL scaler selection when scalingMode is 3. An empty string selects SyncTERM Blocky, Pointy selects the edge-aware scaler, Nearest selects nearest-neighbor scaling, and a relative .slangp path selects a local preset under Menu.fileLocations["scalers"].

scrollbackLines, modemRate

Scrollback capacity is 1 through INT_MAX. Modem DTE rate is 0 through UINT32_MAX; zero means the current or default communications-port rate.

transferSuccessKeypressTimeout, transferFailureKeypressTimeout

Stored transfer completion acknowledgement preferences in seconds, from 0 through INT_MAX. Defaults are 0 for success and 60 for failure. These properties use the normal snapshot, apply, save and reload rules; they persist as TransferSuccessKeypressTimeout and TransferFailureKeypressTimeout under [SyncTERM]. The shipped Wren transfer window currently uses its own wait rather than these preferences.

kdfShift

The effective scrypt cost exponent for encryption rewrites; accepted range is 8 through 20. Unsupported older persisted specifications report the effective default of 15. This is policy, not the loaded file’s KDF; use Menu.encryptionInfo for actual metadata. Changing it rewrites an encrypted personal list using the current password when the setting is applied. An older persisted KDF specification is preserved when another setting changes; assigning kdfShift replaces it with scrypt-Nn.

customRows, customColumns, customFontHeight, customAspectWidth, customAspectHeight

Custom text-mode geometry. Rows are 14..255, columns are 40..255, font height is exactly 8, 14, or 16, and both aspect values are 1 through INT_MAX.

frameColor, textColor, backgroundColor, inverseColor, lightbarColor, lightbarBackgroundColor

Palette indexes used to construct the built-in Classic Theme. Frame, text, and lightbar foreground use Menu.colors, whose Default entry is index 16. Background, inverse, and lightbar background use Menu.backgroundColors, whose Default entry is index 8. The C theme loader resolves those sentinels. Persisted numeric values outside the corresponding range also resolve to the role default. File themes are independent sparse overlays on the compiled default.

The six values are persisted under [ClassicTheme]. On load, each missing key falls back independently to the same key under the former [UIFC] section, so a partial new section does not discard old preferences. The next successful Program Settings save writes all six [ClassicTheme] values and removes [UIFC]. A failed save leaves the existing file unchanged.

Program Settings includes an Amiga Fonts manager. User-installed families live under fonts/amiga/ beside the active syncterm.ini; the 11 bundled families (39 strikes) are compiled into SyncTERM and are not copied there. The per-BBS SkyPix Font choice stores Profile.amigaFont (family name, default Pearl.font) and Profile.amigaFontSize (exact strike height, 1..65535, default 8). Initial selection tries an exact installed name/height, an exact bundled strike, then Pearl 8; it does not stretch a neighbouring size. Reset restores that configured initial strike. Unavailable remote font requests also fall back to it. A selected font remains valid if its installed package is subsequently replaced or removed. Catalog queries and management are menu-only; connected scripts cannot import this interface.

The host supplies display catalogs rather than requiring scripts to duplicate platform-dependent enum tables:

Menu member Result

canvasModes

Ordered [ScreenMode, displayName] rows describing pixel canvases/aspects for the SkyPix editor; text columns/rows derive from the selected Amiga strike. Use each row’s value rather than its position as the mode ID.

rip3ScreenModeChoices, rip3ScreenModeChoices(customScreenMode)

Screen-mode picker rows with square pixels. Current uses the live console geometry. Pass a profile or draft’s five-value Custom geometry to filter Custom for that entry. The getter and a null argument use Program Settings.

screenModeChoices

Ordered [ScreenMode, displayName] rows for screen-mode pickers. CGA 80x25 appears immediately before EGA 80x25; values retain their stable IDs.

screenModes, cursorStyles, scalingModes

Lists of display names indexed by the corresponding numeric setting.

connectionTypes, addressFamilies, rates, musicModes, graphicsModes, flowControls, parities, fontsCatalog, encodings, logLevels

Lists of [value, displayName] rows for directory-entry editors. connectionTypes omits the unspecified value 0 and retains protocol IDs. fontsCatalog uses the loaded conio font index as value; a BBS’s font property remains the display-name String. encodings omits pipe-glyph variants and Prestel’s separated G1 set; UTF-8 is value 255.

fontsForEncoding(encoding), fontEncoding(name)

The former returns compatible [selector, displayName] rows, including configured custom fonts for every encoding and every built-in font for UTF-8. The latter returns a built-in font’s canonical encoding number, or null for a custom or unknown name. The editor coordinates these with screen mode and graphics; setting the raw BBS properties individually does not.

amigaFonts

Fresh List of immutable AmigaFontFamily metadata snapshots. A family has name, sizes (all available heights), installedSizes, source ("bundled", "installed" or "mixed") and error (null or MenuError). Size Lists are fresh values; corrupt installed packages retain their error.

installAmigaFont()

Open the local Amiga .font family picker. Return a family snapshot on success, null on cancellation, or MenuError. Replacement requires the picker confirmation. Every referenced bitmap strike is validated before publication; malformed, colour and outline fonts are rejected. This imports the selected family and its confined relative files, with no script-supplied pathname.

removeAmigaFont(family)

Remove the installed portion of the current family snapshot; return null or MenuError. Bundled fonts cannot be removed. A snapshot retained across another install/remove operation must be reacquired before removal.

defaultPort(connectionType)

Return the built-in default port for a connection-type value. RLogin uses 513, Telnet 23, SSH 22, MBBS GHOST 65535, Telnet TLS 992, and MQTT 8883. Types without an inherent network port return zero.

serialRates(device)

Open the named serial device and return its supported rates as [value, displayName] rows, including Current as rate zero. If the device cannot be queried, return the normal rates catalog.

flowControlsNoRts

Return the [value, displayName] flow-control rows valid for a 3-wire serial connection: XON/XOFF and None. The shipped editor does not replace an existing RTS/CTS value unless the user accepts a new choice.

paletteDefaults(screenMode)

Return [minimumColorCount, colors] for a screen mode. colors is a 16-element List of mode-specific 24-bit RGB defaults; the minimum is 16 for normal modes, 8 for Prestel, and 4 or 2 for the corresponding Atari palettes. Returns null when the mode cannot be mapped.

outputModes

Build-dependent List of [value, displayName] rows for ordinary application output backends. Headless and libretro are intentionally omitted. Assign only a value present in this list to Settings.outputMode; the selected backend is used on the next startup, not switched while the application is running.

audioModes

Build-dependent List of [bit, displayName] rows for selectable audio backends, in the engine’s preference order.

midiModes

Build-dependent List of [bit, displayName] rows for compiled MIDI methods in playback preference order. Reading this catalog does not open a device or load a MIDI library. There is no Wren MIDI playback or routing API.

dosShellAvailable

Bool. True in the persistent menu VM when the static libdosbox emulator can run on the current bitmap display and safe mode is off.

dosShell()

Open an interactive DOS prompt in the local menu. Returns an integer status after the guest exits and the menu display is restored. Zero indicates success. See the DOS drive mappings.

buildOptions

List of [category, displayName, enabled] rows describing this executable’s fonts, crypto, terminal, video, input, audio and MIDI build features. For optional libraries, enabled reports compiled support without opening the library or a device. Rows cover DDO F/X module playback and package extraction, controller input libraries, GLX, Wayland EGL, Slang presets and the testing bitmap backend. MIDI labels include runtime-loaded, static, shared or system linkage when compiled; each row retains exactly three elements. For decoder availability, use PixelBuffer.jxlSupported instead.

licenses

List of [componentName, fullNoticeText] rows embedded in this executable. Available offline and in safe mode. The SyncTERM Unicode OFL notice is included only when SYNCTERM_ENABLE_UNIFONT is enabled. Returned Lists are independent copies; modifying them does not change the embedded notices.

maxPathLength

Build-specific MAX_PATH value used by menu-backed path fields.

encryptionAvailable

Bool indicating whether this build exposes personal-list encryption.

colors, backgroundColors

Foreground and background color-name Lists, including their final Default entries.

currentScreenMode

Current SyncTERM screen-mode enum value.

setScreenMode(mode)

Apply a concrete screen mode immediately and restore the configured default cursor. ScreenMode.current is not accepted. Returns null or ScreenError; a failure can follow changes to one logical console.

fileLocations

Map containing globalList, personalList, configuration, download, cache, globalRip, keys, scripts, scalers, and themes paths for display. These Strings do not confer file-open authority.

Controller mapping in syncterm_menu

Menu.controllers lists attached devices as [localId, label] pairs. An empty list means zero devices and null means no provider. Menu.controllerFields(id) returns one row per physical control in HID descriptor order or XUSB provider order, containing its label, binding index (−1 if unassigned), inversion flag and current preview value (null if unknown). Each physical hat also has four button fields appended after the descriptor fields, one per cardinal direction. A diagonal presses both adjacent directions. Libretro devices expose no editable fields.

Menu.controllerTargets(id, field) lists compatible targets as [bindingIndex, label, kind]. Use field −1 for all targets. Kinds 0, 1, 2 and 3 denote button, centered axis, one-way axis and hat respectively. Menu.controllerHatButton(id, field, direction) returns the button field for a cardinal direction of a hat, or −1 for a non-hat, diagonal or neutral. Menu.armController(id) starts identification using the current baseline. Menu.armController(id, target) captures only fields assignable to that target. Pass −1 to capture any control. Menu.controllerMotion(id) returns [field, value], with field −1 until a new actuation. Hat preview and captured values are clockwise directions 0..7 from up, with −1 for neutral.

Menu.bindController(id, field, target, inverted) applies a binding. Target −1 clears it. Assigning an occupied target moves it to the selected field. The method returns true on success, null if the device disconnected, or a MenuError if saving failed. Safe mode applies the mapping in memory.

Theme storage and file syntax are documented in Themes.adoc.

Menu.themes refreshes the C-owned catalog and returns a List of rows in the form [filename, name, author, description, version, error], or MenuError if refresh fails. Native failure preserves the previous catalog; already returned rows remain usable. The built-in Classic Theme has an empty filename. Optional metadata is null when absent. An invalid or missing theme has an error String and cannot be selected, but remains available for display in the browser.

Menu.selectedThemeFile returns the committed filename, or an empty String when Classic or a cloud package is selected. Menu.selectedThemePackage returns the committed repository/id, or an empty String for Classic and local files. Menu.previewTheme(filename) installs a temporary process-wide preview and returns null/MenuError without changing the committed selection. Menu.cancelThemePreview() restores the committed theme. Both operations advance Host.themeGeneration when they change the active snapshot.

Menu.selectTheme(filename) validates the catalog entry, writes [SyncTERM] ThemeFile, and commits the preview as one operation. Selecting Classic removes the key. It returns null/MenuError. In safe mode the running selection changes but the INI file is not written. A successful selection advances both the theme and settings generations, so scripts should reacquire outstanding Settings snapshots. Selection failure preserves its original native reason and existing restoration attempts; messages describe failed restoration if detected. No new rollback or unchanged-file guarantee is made.

Menu.deleteTheme(filename) removes a local theme file and returns null/MenuError. Deleting the selected file first commits and saves Classic Theme. If deleting the file then fails, Classic remains selected and saved while MenuError reports the deletion failure and the completed Classic selection/save.

Menu.refreshCloudThemes() refreshes the official manifest, updates cached packages whose SHA-256 changed. It returns null for clean native success, a String for native success with a warning, or MenuError for native failure. A warning may accompany a usable cached manifest. The binding does not invent a numeric reason for warning text whose underlying status C has already discarded. Menu.cloudThemes returns a fresh List of read-only CloudThemeEntry live views in the menu VM. They have no public constructor, setters or positional indexing. Local Menu.themes rows keep their existing interface. The native catalog is initialized from the cached manifest during startup, without fetching the manifest or packages. Downloaded packages are therefore available before opening Online Themes. Missing or invalid optional catalog metadata does not prevent restoring the previously selected cached theme.

Property Meaning

package, name, author, description, version

Native package identity and descriptive metadata. Optional fields are null when absent.

sourceUri

The source URI from the manifest, or null when unavailable.

expectedSha256

The expected SHA-256 hexadecimal manifest text, preserving its spelling and case. It is not a freshly computed cached-file digest. Null when unavailable.

cached, updateAvailable

Live native cache-state Bools; reading them does not inspect files or download.

error

Native catalog diagnostic text, or null. It does not manufacture a numeric status for a diagnostic whose underlying native reason is unavailable.

Text fields create Wren Strings only on access, validating UTF-8 and normalizing to NFC. A conversion failure returns MenuError with the actual status in code and nativeCode. This also applies to reading the diagnostic text in error. A selected package absent from the manifest can have null sourceUri and expectedSha256. Metadata views retain no borrowed strings or parsed-theme pointers and grant no file or network authority.

Successful replacement of the native cloud catalog makes old views stale, including refreshes returning a warning. A failed refresh before replacement preserves them. Stale field reads abort; reacquire through Menu.cloudThemes. In-place cache, selection and deletion updates remain visible without replacing the view. Changes to the displayed theme alone do not invalidate catalog views. Captured Strings remain independent after updates or replacement. Property reads perform no downloads, cache checks or file reads.

Menu.previewCloudTheme(package) previews a validated cached package and returns null/MenuError. Menu.cacheCloudTheme(package) downloads and validates a package without selecting it. Menu.selectCloudTheme(package) does the same as needed, writes [SyncTERM] ThemePackage, removes ThemeFile, and commits the selection. Menu.copyCloudTheme(package) returns an unsaved ThemeDocument populated from the cached package, or MenuError. Caching and selecting return null/MenuError. These catalog and document operations are menu-VM capabilities; the cache location is never exposed as general filesystem authority.

Menu.deleteCloudTheme(package) removes a cached package so it appears in Online Themes again, returning null/MenuError. Deleting the selected package first commits and saves Classic Theme. If deleting the cache file then fails, Classic remains selected and saved; MenuError describes that completed step and preserves the deletion failure. Both deletion operations are unavailable in safe mode.

The shipped Themes browser combines Menu.themes with cached entries from Menu.cloudThemes, using distinct identities for Classic, local files, and packages when tracking its selection. Its Online Themes browser displays only Menu.cloudThemes entries whose cached member is false. Downloading a package therefore moves it from the online-only browser to the main Themes browser. Both browsers publish the highlighted row’s description through the main menu’s comment callback and reserve the comment row when sizing their shadowed panes.

Menu.newThemeDocument() returns a new C-owned ThemeDocument containing a minimal sparse overlay on the compiled default, or MenuError on native failure. Its filename is empty and it is dirty until saved. Menu.openThemeDocument(filename) accepts the nonempty basename of a file accepted by the current theme loader, returning ThemeDocument/MenuError. Empty names and invalid arguments abort the Fiber. Menu.copyCloudTheme likewise returns ThemeDocument/MenuError. These constructors and all document methods are menu-VM capabilities; documents cannot be created or passed into the connected or picker VMs.

ThemeDocument.metadata(field) and setMetadata(field, value) use field IDs 0 Name, 1 Author, 2 Description, and 3 Version. The optional fields return null when absent; setting an optional field to an empty String removes it. Name cannot be empty. Metadata/style/glyph mutation and import return null/MenuError with the portable native reason, replacing error Strings in v2. Existing type/range/enum validation aborts remain; native semantic failures are recoverable values.

ThemeDocument.styles returns rows [role, builtin, present, font, legacyAttr, foreground, background]. present is a bit mask for fields 0 Font, 1 LegacyAttr, 2 Foreground, and 3 Background. setStyle(role, field, mode, value) uses mode 0 to remove the file value and restore the compiled default, mode 1 to write inherit, and mode 2 to write the supplied numeric value. addStyle(role) creates a custom role with inherited fields. removeStyle(role) removes only a custom role.

ThemeDocument.glyphs returns rows [name, builtin, present, cp437, ascii, codepoint]. Its present bits are 0 CP437, 1 ASCII, and 2 Codepoint. setGlyph(name, field, mode, value) accepts modes 0 Default and 2 Explicit; mode 1 is not meaningful for glyphs. addGlyph(name, ascii) creates a custom glyph with its required ASCII value; the other representations can then be set explicitly. removeGlyph(name) removes a custom glyph.

ThemeDocument.themeData returns a fresh Wren theme-data snapshot for the draft. Theme.fromData(data) decodes such a snapshot without changing the process-wide selected theme. dirty, canUndo, and canRedo report the document state; undo() and redo() return whether they changed it. importTheme(filename) replaces all style and glyph sections from an installed theme as one history entry while retaining the document filename and metadata. It preserves custom definitions and unknown content rather than limiting the import to the built-in registry.

ThemeDocument.save(filename, force) persists only, returning null/MenuError instead of the former [code, error] pair. A null filename saves to the current basename. Native save failures use code == null and their distinct enum in nativeCode; they are not portable IOErr values. The named ThemeSaveErr constants preserve the native enum: ok=0, invalid=1, conflict=2, exists=3, readOnly=4 and io=5. Success is null. Host safe-mode rejection uses IOErr.readOnly with nativeCode null, rather than inventing a native call/result. A true force permits overwriting after conflict or exists; it bypasses neither validation nor safe mode.

Save preserves untouched source text, writes through the destination without replacing its filesystem entry, and clears editing history after successful write and close. Symbolic/hard links retain their relationship; write/close failure can leave partial contents. Saving does not change the active theme or its generation.

ThemeDocument.activate() installs an independent native copy of the document’s resolved in-memory theme and returns null/MenuError. It requires a clean, saved document matching the manager’s committed local theme under the existing platform filename identity rules. Unsaved, dirty, differently selected, Classic and cloud selections return IOErr.invalidArgument. Allocation failure leaves the active theme, preview and generation unchanged. Success clears temporary preview and advances Host.themeGeneration once; selection, Settings generation, document history and files are unchanged. Activation performs no filesystem I/O, including when the backing file has been removed or edited externally, and is allowed in safe mode. Later document edits or collection do not modify the installed copy. Native APIs continue to own manager/document lifetime; no new script resource owner is created.

The editor confirms replacement only for conflict/exists, then saves with explicit force if accepted. After saving it activates only a matching selected local theme, using the native identity guard rather than Wren filename case assumptions. Failure to activate is reported as saved-but-not-activated; the document stays clean and persistence is treated as complete. There is no automatic resave or activation retry.

var failure = document.save(null, false)
if (failure != null) {
  System.print(failure.message)
} else {
  var activation = document.activate()
  if (activation != null) System.print(activation.message)
}

The shipped menu_theme_editor module keeps the document rows as the editing source of truth and builds a separate Theme.fromData(document.themeData) snapshot for each draft refresh. Its cascade inspector distinguishes file values, explicit inheritance, compiled defaults, compiled inheritance, and absent roles for every field. The interactive widget preview reports the theme role associated with its focused control and can return that role to the exhaustive atlas. Glyph values are chosen as raw bytes from 16-column CP437 and printable-ASCII grids rather than entered as decimal integers. These operations remain menu-VM-only because they retain and modify a ThemeDocument.

Menu.encryptionInfo returns a fresh, read-only ListEncryptionInfo snapshot of the personal list in memory, or null if no list model is loaded. Plaintext is a snapshot with format == ListEncryptionFormat.plain, algorithm == MenuEncryption.none, keyBits == 0, and kdf == ListEncryptionKdf.none. It is distinct from an absent model. This getter performs no I/O or rewrite.

Snapshots have no public constructor or setters. They copy scalar metadata, retain no secrets or borrowed pointers, and remain usable and unchanged after reloads, encryption changes and failed operations. Invalid native metadata, including integers outside Wren’s exact Number range, aborts the calling Fiber. These classes and Menu operations are available only in the menu VM.

Snapshot property Result

format

ListEncryptionFormat.plain (0), .v1 (1), or .v2 (2).

algorithm

A MenuEncryption cipher value.

keyBits

Key length in bits, or zero for plaintext.

name

Not Encrypted, 3DES, IDEA, CAST-<bits>, RC2-<bits>, RC4-<bits>, AES-<bits>, or ChaCha20.

kdf

ListEncryptionKdf.none (0), .pbkdf2Sha256 (1), or .scrypt (2).

iterations

Actual PBKDF2 iteration count; otherwise null.

costLog2

Actual scrypt cost exponent (N = 2^costLog2); otherwise null.

blockSize

Actual scrypt parameter r; otherwise null.

parallelism

Actual scrypt parameter p; otherwise null.

rewriteRecommended

Native recommendation Bool; reading it performs no rewrite.

MenuEncryption defines none (0), tripleDes (1), idea (2), cast (3), rc2 (4), rc4 (5), aes (6), and chacha20 (7). Legacy cipher values identify loaded files; they do not enable legacy writes. The former Menu.encryptionAlgorithm, Menu.encryptionKeySize, and Menu.encryptionName getters are removed in v2. Use one snapshot for consistent reporting:

var info = Menu.encryptionInfo
if (info != null) System.print(info.name)

The shipped encryption dialog shows Change Password only when encryption is available and the loaded combination is writable: AES-128, AES-256, or ChaCha20. Unsupported loaded combinations (including AES-192) retain explicit conversion and decryption choices. SyncTERM reads the file metadata; users do not need to parse or enter headers.

Menu.setEncryption(algorithm, keySize, password) rewrites the current personal list and returns null/MenuError. AES accepts 128- or 256-bit keys; ChaCha20 accepts zero to select its fixed 256-bit key (explicit 256 is also accepted), and unencrypted lists use key size zero. The current kdfShift is used when encrypting, changing algorithms, or changing a password. password may be null to reuse the password already held by the host. Enabling encryption fails if neither source supplies a non-empty password. A successful rewrite updates the current algorithm, key size, and held password; a failure leaves them unchanged. The operation is disabled in safe mode, where it returns IOErr.readOnly without rewriting the list or changing the algorithm, key size, or held password.

Menu.webLists returns a fresh List of [name, uri] rows. Names must contain 1..50 Unicode scalars and at most 100 UTF-8 bytes, be canonically caseless-unique, and have no controls, leading or trailing Unicode whitespace, or =/:, and cannot begin with ; or [. System List is reserved. Indexes refer to the order shown by that returned List. Menu.webListsDirty reports whether the in-memory list has unpersisted edits.

Method Description

addWebList(name, uri, index)

Fetch the URI into the web-list cache and insert the in-memory entry. Returns null on success or an MenuError.

updateWebList(index, uri)

Change an in-memory entry’s URI. Returns null/MenuError. It does not refresh the cached list.

deleteWebList(index)

Remove an in-memory entry. Returns null/MenuError.

saveWebLists()

Persist the in-memory entries to the WebLists INI section. Returns null/MenuError. A failed write leaves webListsDirty set so it can be retried.

refreshWebList(index)

Fetch the current URI into the cache without changing configuration. Returns null on success or an MenuError.

In safe mode, add, update, and delete still update the running configuration, and add still performs its initial fetch. saveWebLists() returns IOErr.readOnly without writing syncterm.ini, so those changes last only for the current process. Refresh remains permitted. No web-list method exposes its cache pathname as a file capability.

Each menu host owns a custom-font draft separate from the loaded console font slots and from unrelated program settings. Menu.fonts returns a fresh List of MenuFont handles. Menu.fontsDirty reports whether that draft has unsaved edits.

Method Description

Menu.canCreateFont

Return whether another custom-font record can be added. This includes the available custom slots and safe mode.

Menu.createFont(name, index)

Insert a blank custom font at index and return its handle. Names contain 1..50 Unicode scalars and at most 100 UTF-8 bytes, cannot begin or end with Unicode whitespace, cannot contain controls, [ or ], and are unique under Unicode canonical caseless matching. Returns MenuFont/MenuError; invalid arguments abort the fiber.

Menu.saveFonts()

Merge only the draft’s Font: sections into syncterm.ini, preserving unrelated file content and unsaved runtime settings. Returns null/MenuError. Failure leaves the draft dirty; success clears it. This call does not activate fonts. The native truncate-then-write policy can leave a partial file on failure.

Menu.activateFonts()

Activate the installed custom-font configuration using the existing native loader. Returns null/MenuError. Failure preserves previous live mappings. Native missing/unsupported bitmap skip rules are unchanged. The bundled editor saves first, then activates, and reports activation failure without resaving.

Menu.reloadFonts()

Discard unsaved font edits and reread only the Font: sections transactionally. Unrelated settings and loaded font slots are unchanged. Returns null/MenuError.

MenuFont.name

Read/write the display and INI-section name using the same nonempty, INI-safe and case-insensitively unique rules as createFont.

MenuFont.path(slot)

Configured pathname String for display, or null. Returning a pathname does not mint a File and confers no open authority.

MenuFont.setFile(slot, file)

Assign a path from a live, read-authorized File, normally returned by Host.pickFile. Returns null/MenuError. The picker mask guides selection. Bitmap size is checked when the font is loaded, not while editing the draft.

MenuFont.clearFile(slot)

Clear one configured size and return null/MenuError.

MenuFont.delete()

Remove the record from the in-memory model and return null/MenuError. Call Menu.saveFonts() to persist the deletion.

MenuFontSlot values and their picker masks are:

Constant Code Bytes Typical mask

eightByEight

0

2048

*.f8

eightByFourteen

1

3584

*.f14

eightBySixteen

2

4096

*.f16

twelveByTwenty

3

10240

*.f20

Create and delete advance the font-model generation, invalidating all previously obtained MenuFont handles. Rename, file assignment, clear, and save preserve handles. Font mutation, activation and persistence return IOErr.readOnly in safe mode; reload remains available because it only reads the existing configuration.

Profile properties use the following numeric constants in both menu and connected VMs. Prefer the catalogs returned by Menu when constructing a user-facing choice list.

ConnType

Constant Code Description

unknown

0

Unset / not yet decided.

rlogin

1

RLogin (TCP/513) — classic BBS auth-on-connect protocol.

rloginReversed

2

RLogin with the handshake byte order reversed (some servers).

telnet

3

Telnet (TCP/23) — IAC negotiation in NVT mode.

raw

4

Raw TCP — no protocol layer; bytes pass straight through.

ssh

5

SSH-2 — encrypted with password / key authentication.

sshNoAuth

6

SSH-2 with the "none" authentication method (anonymous).

modem

7

Phone modem dial-out via AT commands.

serial

8

Direct serial port.

serialNoRts

9

Serial without RTS/CTS hardware flow control.

shell

10

Local subprocess (shell command).

mbbsGhost

11

MajorBBS / Worldgroup "GHost" client interface.

telnets

12

Telnet over TLS (TCP/992).

mqtt

13

Synchronet node terminal stream over MQTT 5/TLS.

wsTelnet

14

Binary Telnet over WebSocket (TCP/80).

wssTelnet

15

Binary Telnet over WebSocket with TLS (TCP/443).

Emulation

Constant Code Description

ansiBbs

0

ANSI-BBS — ANSI X3.64 / VT-style escape sequences with PC-style color attributes. The default.

petascii

1

Commodore 64 / 128 PETSCII control codes.

atascii

2

Atari 8-bit ATASCII control codes.

prestel

3

UK Prestel / Viewdata teletext — block mosaic graphics, double-height, conceal.

beeb

4

BBC Micro Mode 7 teletext.

atariVt52

5

Atari ST GEM VT-52 emulation.

BBSListType

Constant Code Description

user

0

User-edited entry from the user’s BBS list.

system

1

Entry from a shared, system-web or named-web list. Read-only in its source directory.

TLSVersion

Constant Code Description

unknown

0

No authenticated TLS version has been recorded.

tls12

1

TLS 1.2.

tls13

2

TLS 1.3.

ScreenMode

Standard modes encode their dimensions in the name (e.g. c80x25 = 80 columns × 25 rows). Codes are stable enum values.

Constant Code Description

current

0

"Don’t change" — keep the current mode.

c80x25

1

80×25 (CGA / VGA standard).

lcd80x25

2

80×25 with LCD-style cell aspect (SyncTERM-specific).

c80x28

3

80×28 (extended VGA).

c80x30

4

80×30 (extended VGA).

c80x43

5

80×43 (EGA-extended).

c80x50

6

80×50 (VGA 8-pixel-tall cell).

c80x60

7

80×60 (extended VGA).

c132x37

8

132×37 (Super VGA).

c132x52

9

132×52 (Super VGA).

c132x25

10

132×25.

c132x28

11

132×28.

c132x30

12

132×30.

c132x34

13

132×34.

c132x43

14

132×43.

c132x50

15

132×50.

c132x60

16

132×60.

c64

17

Commodore 64 (40×25 PETSCII).

c128_40

18

Commodore 128 (40-column mode).

c128_80

19

Commodore 128 (80-column mode).

atari

20

Atari 8-bit native (40×24 ATASCII).

atariXep80

21

Atari 8-bit with XEP80 80-column expansion box.

custom

22

Custom dimensions configured per-BBS.

cga80x25

32

CGA 80x25, 640x200 with an 8x8 cell and 4:3 display aspect.

ega80x25

23

EGA 80×25 with hardware-accurate pixel aspect (8×14 cell).

vga80x25

24

VGA 80×25 with hardware-accurate pixel aspect (8×16 cell).

prestel

25

Prestel teletext (40×24).

beeb

26

BBC Micro Mode 7 (40×25 teletext).

atariSt40x25

27

Atari ST 40×25 (low-res color).

atariSt80x25

28

Atari ST 80×25 (medium-res color).

atariSt80x25Mono

29

Atari ST 80×25 monochrome (high-res).

amiga640x200

30

Amiga 640×200 pixel canvas, displayed at 4:3.

amiga640x400

31

Amiga 640×400 pixel canvas, displayed at 4:3.

AddressFamily

Constant Code Description

unspec

0

As per DNS (default): connect only to the system resolver’s preferred address, IPv4 or IPv6.

inet

1

Connect only to the preferred IPv4 address.

inet6

2

Connect only to the preferred IPv6 address.

happyEyeballs

3

Race IPv4 and IPv6 addresses with attempts staggered by 250 ms. Use the first successful connection and close the others. Extra connections can allocate BBS nodes or activate serial bridges; this mode is opt-in.

MusicMode

Controls how SyncTERM interprets ANSI music sequences (CSI …​ character).

Constant Code Description

syncterm

0

SyncTERM’s strict mode — only the CSI MNML sequence triggers music; less-anchored sequences are passed through as text. The default.

bansi

1

BANSI-style — older BBS music parsing rules.

enabled

2

Most permissive — all forms accepted.

GraphicsMode

Constant Code Description

none

0

Remote graphics disabled for this connection.

v1

1

RIPscrip v1.54 compatibility mode.

v3

2

SyncTERM’s "idealized" RIP v3 — bug-fixed and extended; not bug-compatible with v1.54.

skypix13

3

Practical SkyPix dialect, with Kickstart 1.3 rendering.

skypix31

4

Practical SkyPix dialect, with Kickstart 3.1 rendering.

igs221

5

IGS 2.21 Atari ST graphics; see coverage.

big103

6

BIG 1.03 terminal graphics; see current coverage.

ddofx20

7

DDO F/X 2.0. See current coverage.

Selecting IGS presets Atari ST 40x25 (320x200), Atari ST encoding and font. The ST 80x25 colour and monochrome modes are also available. UTF-8 can be selected while retaining ST glyphs. IGS and RIP enter the same pre-ANSI receive stage; ordinary bytes continue to the selected base emulation. Profile.graphics stores the entry’s initial engine. CTerm.graphicsMode reports the engine active on the connection, including changes negotiated with the graphics APCs in the terminal protocol reference.

Selecting BIG presets ScreenMode.ega80x25 (640x350), CP437 and the original IBM console font. ScreenMode.cga80x25 (640x200) and ScreenMode.c80x30 (640x480) are also supported initial profiles; UTF-8 retains the CP437 glyph mapping. An unsupported or Current profile starts in EGA without rewriting the saved profile. BIG mode installation selects the exact 8x8, 8x14 or 8x16 ROM bank. A different console font/codepage or unsupported screen choice in the editor switches back to ordinary emulation. BIG shares the same pre-ANSI receive insertion as IGS/RIP. All45 BIG command entries have native integration; the coverage ledger records verification and the native protocol adaptations.

Both SkyPix variants use the practical protocol recorded in SkyPix conformance, Pearl 8 by default, measured native-glyph wrapping and 50 Hz delays including short delays. Command 17 selects eight/sixteen colours; brush palettes apply on first blit and promote depth when required. Kickstart differences concern ellipse arithmetic and per-character proportional-glyph overhang. Selecting SkyPix initially presets ScreenMode.amiga640x200 (4:3) and Latin-1. ScreenMode.amiga640x400 is also available at 4:3, with an 80×50 system grid of 8×8 cells. Native Amiga font strikes retain their pixel dimensions in either mode; the 400-line canvas provides more vertical space. Screen Mode selects the pixel canvas, Encoding selects the wire encoding, and Font selects an installed or bundled Amiga family/height for initial text and reset. These choices remain editable. The system cell grid comes from the screen mode, independently of the native Amiga text metrics; graphics clip to the drawable area. The optional status row uses the last system-cell row inside the selected mode; resolution and aspect ratio remain unchanged. Ordinary Profile.font remains available for other graphics modes. Classic Amiga fonts are byte-indexed and carry no charset tag; codepage connections use that codepage’s glyph positions, and UTF-8 text uses Latin-1 glyph mapping. C1 positions may contain glyphs even when a selected terminal decoding mode interprets those bytes as controls. CTerm.skypix reports the selected graphics engine, rather than inferring it from a remote command. RIP sessions do not interpret SkyPix commands.

SkyPix command-16 transfers accept IFF brushes (type 1), IFF sound (type 2), FutureSound samples (type 3), and general files (type 20). All use CRC XMODEM and the active BBS’s shared SkyPix cache subdirectory, matching SkyTERM’s single BRU: destination. Completed files are reused; partial or invalid brush downloads are discarded. Types 2, 3 and 20 preserve cached bytes, including XMODEM padding, without replacing the current brush. Type 3 also loads the sample after receipt or on a cache hit; an unsuccessful load leaves the file cached and retains the previous sound. Type 2 has no IFF sound decoder. They do not use RIP asset framing. Gadget command 22 retains the definition in slot 1–20 and draws its foreground rectangle; clicks still report raw controller-1 pixel coordinates. Controller-2 menu reports and local execution of stored gadget commands remain unsupported. See SkyPix conformance for the precise supported subset.

Type-3 samples contain a big-endian unsigned 32-bit PCM-byte count and unsigned 16-bit rate, followed by signed 8-bit mono PCM. The declared payload must be present, positive, and no larger than 4 MiB; the rate must be nonzero. Odd lengths are accepted and trailing bytes are ignored. Command 9 uses only its loop count and plays the entire sample. Zero deliberately means one play; the originals instead wait indefinitely for continuous playback.

SkyPix uses the shared effects stream (logical channel 1), independently of channel-0 music, with its existing gain/pan. A custom incremental linear converter uses the originals' 16-bit period (3579545 / rate) & 65535 and converts its effective rate to 44100-Hz stereo. It does not emulate analog filters or artificial gaps at Amiga device-write boundaries. Remote parsing waits for playback and backend latency while local UI continues. Synchronous connected/menu/picker input waits service pending audio without consuming remote input or extending the requested input deadline. Reset/EOF cancel playback; reset/destruction release the loaded sample. Disabled or unavailable audio skips playback and the wait. There is no new script audio API.

Parity

Constant Code Description

none

0

No parity bit (8N1 framing).

even

1

Even parity bit.

odd

2

Odd parity bit.

FlowControl

Constants for the numeric Profile.flowControl setting.

Constant Code Description

rtsCts

0

RTS/CTS hardware flow control.

xonXoff

1

XON/XOFF software flow control.

both

2

Hardware and software flow control.

none

3

No flow control.

LogLevel

Standard syslog severity values (RFC 5424). emergency is the most severe; debug is the least.

Constant Code Description

emergency

0

System is unusable.

alert

1

Action must be taken immediately.

critical

2

Critical condition.

error

3

Error condition.

warning

4

Warning condition.

notice

5

Normal but significant.

info

6

Informational.

debug

7

Debug-level diagnostic.

Host

Module-private bridge for state the host owns but Wren shouldn’t be able to construct directly. The members below are foreigns; the Cache / Download module-level vars (see below) are pre-bound from these at module load.

Member Description

Host.themeGeneration

Monotonic process-wide generation for the active theme. Preview, cancellation, and committed selection changes advance it.

Host.themeData, Host.defaultThemeData

Return fresh immutable-by-ownership snapshots of the active theme and compiled fallback respectively. Each result is [styles, glyphs]. A style row is [role, font, legacyAttr, foreground, background], with null representing inheritance. A glyph row is [name, primary, asciiFallback]. These bindings are available in all three VMs. Wren may mutate its returned Lists, but that cannot change C-owned theme state or snapshots returned to another VM.

Host.cacheDirectory

Returns a fresh Directory for the active BBS cache pathname (SYNCTERM_PATH_CACHE). No Wren-visible Directory constructor exists, so this is the only path to that root. Use the module-level Cache binding instead in most code.

Host.downloadDir

Returns a fresh Directory rooted at the BBS’s configured DownloadPath, with the relaxed-name predicate enabled (1..255 bytes; no path separators / NUL / control bytes / . / .. / Windows reserved devices, but spaces / leading dots / parens etc. allowed). Returns null when DownloadPath is empty, equal to the user’s $HOME, or doesn’t exist as a directory on disk — consumer code uniformly null-checks Download before use, so routing the configured-but-missing case through the same null gate keeps every call site simple. Used as the module-level Download binding.

Host.uploadPath

The BBS’s configured UploadPath as a String, or null when unconfigured. Pass to pickFile / pickFiles as initialDir. No upload-side Directory is exposed on purpose — uploads must go through the picker (which mints a per-file consent token); scripts can’t enumerate UploadPath or open files from it directly.

Host.pickFile(initialPath, mask, opts)

User-consent escape hatch for "upload from anywhere": invokes the isolated picker VM and returns a File whose path is the absolute path the user picked, or null on cancel. Picker startup/recovery failures, including failure to restore the menu console, raise a runtime error rather than reporting user cancellation. The same error contract applies to pickFiles and pickSavePath. initialPath may be a String path, a Directory foreign (uses its path; handles Cache lazy-resolve), or null (defaults to Session.current.profile.ulDir). An existing file path opens its containing directory with that file selected. mask may be null (defaults to *). opts combines the stable FilePickerOptions values documented below. The returned File’s path bypasses the relaxed-name policy; the picker interaction is the local consent boundary, since the user explicitly chose the path. The returned `File is read-only and carries a .token consent token (see "Picker consent tokens" below) when the per-installation signing key is loaded.

Host.pickFile(initialPath, mask, opts, title)

The same consent picker with a caller-supplied title String. The title changes only the picker presentation and grants no additional file authority.

Host.pickFiles(initialDir, mask, opts)

Multi-select counterpart of pickFile. Same argument shape. Returns a non-empty List<File> on OK (each File is read-only and has a .token), or null on cancel / empty selection. allowEntry, confirmOverwrite, and confirmCreate cannot be combined with multi-select.

Host.pickSavePath(initialDir, mask) Host.pickSavePath(initialDir, mask, opts)

Save-mode picker with path entry and overwrite confirmation. The user can pick an existing file or type a new filename. The picker reports create, overwrite, or append consent explicitly, and the caller does not stat the path again. The two-argument form offers overwrite for existing files. Pass FilePickerOptions.allowAppend to the three-argument form to offer Overwrite, Append, and Cancel instead. Returns a write-consent File whose .open() succeeds exactly once, or null on cancel. See Write consent below for the mode rules and single-shot semantics. .token on the returned File is null — write consent is intentionally session-bound and doesn’t replay across sessions.

Host.openLocalFile(token)

Re-construct a File foreign from a consent token previously returned by pickFile / pickFiles via the .token getter. Returns null when the token is invalid (HMAC mismatch, signing key rotated), the file no longer exists, or the file’s content has changed since consent (SHA-256 mismatch). The reconstructed File is read-only. This is the only path by which Wren can construct a File for a path outside the sandboxed Cache / Download roots; the token is the consent.

Host.uploadArrow, Host.uploadArrow = b, Host.downloadArrow, Host.downloadArrow = b

Status-bar transfer-indicator arrows (CP437 ↑ / ↓, painted by the default Status render at the row’s right edge). Generic — any Wren script that knows it’s transferring something can light them; the canonical user is the SFTP queue’s worker fibers, but a Zmodem / HTTP fetcher / etc. could too. Pure Wren-side state on the Host class: both default to false and vanish with the VM at teardown, no C-side reset needed. The session pump renders their current values on its next pass.

Host.safeMode

true when SyncTERM was started with -s (safe mode): no auto-connect, no SFTP key writes, no script-driven external commands. The default status bar surfaces (SAFE) when this is set so the user can see what mode they’re in.

Host.textTerminal

true when the active console backend displays character cells through ANSI, ncurses, or the native Win32 console rather than through a bitmap window. The selected ANSI encoding and ncurses character mode do not affect the result. Stable for the lifetime of the session; native capability read failures return ScreenError.

Host.localControlKeys

true when SyncTERM reserves Ctrl+Q and Ctrl+S for local UI commands. This is currently limited to ANSI and ncurses. The native Win32 console is a text terminal, but it has independent keyboard events and therefore returns false. The main menu and Wren console use this property when installing and displaying their backend-specific bindings. Native capability read failures return ScreenError.

Host.altKeyName, Host.altKeyShort

Display name of the modifier key that produces Alt keycodes on this platform. altKeyName is the long form ("Alt" everywhere except macOS, where it’s "Command" because the Quartz backend maps Cmd to Alt and reserves Option for input composition); altKeyShort is the matching three-letter abbreviation ("ALT" / "CMD", both 3 chars wide regardless of platform). Use the long form in inline help / menu entries and the short form in tight slots like the status bar so menus stay 40-column-safe on Mac.

Host.print(s)

Write s and a newline to standard output, then flush. Distinct from System.print(s), which is captured by the Wren console log buffer (see Wren Console) and never reaches the process’s actual stdout. Host.print bypasses the log and emits to the launching shell — intended for scripts run under syncterm -W that need to report results / progress lines to a test harness or other launching process.

Host.launchScript

Full path of the Wren script supplied via the -W command-line flag, or null when -W wasn’t used. Lets a script that is also embedded for normal Alt+key dispatch detect command-line invocation and run itself immediately: + [source,wren] ---- if (Host.launchScript != null && Host.launchScript.endsWith("foo.wren")) { Foo.run() } ----

Host.logUnread, Host.logUnreadError

Wren-console activity since the user last visited the REPL. logUnread is true when any non-empty append has happened (script print output, hook metrics, etc.); logUnreadError is the subset for compile / runtime errors and stack frames. The default connected status bar and the main menu’s top-right corner paint a CP437 ‼ indicator — red when logUnreadError is set, yellow when only logUnread is set, blank otherwise. Each VM has independent counters. Cleared by visiting that VM’s console pane.

Host.musicNames, Host.musicHelp

ANSI music mode display strings and help blurb, returned as a fresh List<String> indexed by MusicMode and a multi-line String respectively. Same source as the bbslist editor’s music picker (music_names[] and music_helpbuf in bbslist.c), so a Wren-side picker stays aligned with the C-side dialog.

Host.outputRates, Host.outputRateNames

Throttled-output ladder. outputRates[i] is the BPS value (a Num); outputRateNames[i] is the human label (e.g. "115200" for index 10, "Current" for the trailing 0 = no-cap entry). Indexes line up between the two lists. Pass any rate value to CTerm.throttleSpeed = bps. The online_menu Output Rate picker uses these to populate its sub-list.

Host.logLevel, Host.logLevel = n, Host.logLevelNames

Transfer log threshold (0 = Emergency, …​, 7 = Debug) and the matching display labels indexed by the same number. Out-of- range values are clamped on write. The online_menu Log Level picker writes the setter. Each connected VM starts from Session.current.profile.xferLogLevel; live changes affect only that connection’s transfer diagnostic callback, not the stored entry or the independent protocol log threshold.

Host.haveOOII

true: Operation Overkill ][ terminal support is part of the base build.

Host.maxOOIIMode

Highest valid OOII mode value (3). The online_menu wraps the OOII increment back to 0 when it exceeds this cap, so the mode cycle is 0 through Host.maxOOIIMode.

Host.editBBSList()

Suspend terminal byte consumption and enter the persistent trusted menu VM over a saved copy of the connected screen. The connected VM is parked, no Wren or foreign object crosses between VMs, and trusted input barriers discard queued synthetic keyboard and mouse input in both directions. On return, the host restores the terminal screen, title, scrollback configuration, and prior suspension state. This is the default Alt+E path.

Host.sshPublicKey

The first locally-configured SSH public key, as a Map {"algo": String, "blob": String} (e.g. algo: "ssh-ed25519", blob: "AAAA…​"), or null when none is available (no SSH backend, key not loaded, OOM). Used by scripts/auto/connected/sftp_pubkey.wren to append the user’s authorized_keys entry on connect when Session.current.profile.sftpPublicKey is set. Today only ed25519 is exposed; the structured shape lets future RSA / sntrup keys join without breaking consumers.

FilePickerOptions

Public option bits for Host.pickFile and Host.pickFiles. The numeric assignments are stable so scripts may combine or persist them.

Member Value Meaning

none

0

No optional behavior.

maskLocked

1

Display the mask but do not let the user edit or replace it.

maskCaseSensitive

2

Match file and directory masks case-sensitively.

caseSensitiveSort

4

Sort entry names case-sensitively.

selectDirectory

8

Select a directory rather than a file.

pathMustExist

16

Reject a typed path which does not exist.

fileMustExist

32

Reject a typed filename which does not exist.

showHidden

64

Include hidden entries in directory listings.

allowEntry

256

Allow the always-visible Path field to receive focus and accept a typed directory or filename. Single-file pickers which permit a new path (neither pathMustExist nor fileMustExist) also offer New, which edits only the filename in the Path row while keeping the current directory fixed. Enter or OK accepts that filename using the same confirmations as full-path entry.

confirmOverwrite

512

Ask before accepting an existing destination.

confirmCreate

1024

Ask before accepting a destination which does not exist.

allowAppend

2048

Save picker only. When an existing destination is selected, offer Append alongside Overwrite and Cancel.

allowEntry, confirmOverwrite, confirmCreate, and allowAppend are invalid with Host.pickFiles. Host.pickSavePath(initialDir, mask) supplies its save-mode options itself. Its three-argument overload accepts save-picker option bits; currently only allowAppend is meaningful there.

Cache

Module-level Directory injected from C (pre-bound from Host.cacheDirectory), pointing at SyncTERM’s per-user cache directory (SYNCTERM_PATH_CACHE). Use this for script-private state that should survive restarts.

The visible syncterm-cache-name.txt file in each BBS cache records its entry name. It is reserved for SyncTERM and excluded from script cache grants and APC/RIP cache operations. Hash collisions use numbered directory suffixes; scripts receive the directory matching the stored name automatically.

Cache.list returns a Map keyed by entry name; values are File objects for regular files and Directory objects for subdirectories. That’s the read-side handle factory — a script reads existing cache content by indexing into Cache.list, and creates new content with Cache.create(name):

import "syncterm" for Cache, FileError

var entries = Cache.list
if (entries is FileError) Fiber.abort(entries)
var f = entries["greetings.txt"]
var firstRun = f == null
if (firstRun) f = Cache.create("greetings.txt")
if (f is FileError) Fiber.abort(f)
var opened = f.open()
if (opened is FileError) Fiber.abort(opened)
var result = firstRun ? f.write("Hello, world!") : f.read()
var closed = f.close()
if (result is FileError) Fiber.abort(result)
if (closed is FileError) Fiber.abort(closed)
if (!firstRun) System.print(result)

// Subdirectories appear in the same map.  Walk into them by chaining
// `.list` lookups:
//   Cache.list["RIP"]                         → Directory for /RIP
//   Cache.list["RIP"].list["icons.dat"]       → File inside /RIP

There is no Wren-callable factory for Directory — Cache, Download, and Cache.list[someSubdir] (and the analogous Download.list[…​]) are the only paths to one.

Download is a module-level Directory binding pre-bound from Host.downloadDir at import time. It is null when the configured DownloadPath is empty, set to the user’s $HOME, or doesn’t exist as a directory on disk; scripts MUST null-check before use. Its relaxed-name predicate is what makes typical SFTP filenames ("file with spaces.zip", "doc-v1.0.tar.gz") usable as local paths in transfer queues.

There is intentionally no Upload counterpart. All uploads must go through Host.pickFile / Host.pickFiles, which mint a per-file consent token tied to the file’s content hash. The script then enqueues uploads by token (File.token); the worker re-opens the source via Host.openLocalFile(token). Use Host.uploadPath to feed the configured UploadPath to the picker as initialDir.

Filesystem results

Local and remote filesystem APIs use these result conventions. Remote methods return an Operation; the table describes its completed value.

Operation Result

Create/open a resource

The requested resource object or an Error. Local File.open() opens an existing grant and returns null or FileError.

Mutation or close

null on success; FileError locally or SFTPError remotely on failure.

readBytes(count, offset) with positive count

A nonempty byte String, including a successful short read; null at EOF; or an Error. Local readBytes(count) uses the same convention and advances.

Zero-byte read

"", independently of EOF. No native I/O or offset change occurs.

Zero-byte writeBytes / appendBytes

null; no native I/O or offset change. File.write("") still replaces contents with an empty file, and writeLine("") writes a newline.

File.read()

Complete file bytes from offset zero, including "" for an empty file, or FileError.

File.truncate(size)

null after resizing, or FileError; existing buffered output may already have flushed when resizing fails.

File.readLine()

A line String (including "" for a blank line), null at EOF, or FileError.

Directory.contains(name)

Bool for presence/absence; FileError when the query cannot be performed.

Every filesystem error inherits from Error. Check result is Error when either domain is possible, or the concrete class when inspecting its native details. Invalid arguments, invalid names, missing rights and operations on closed/closing streams abort the calling fiber before native I/O. Repeated close is allowed. Property setters return the assigned Number on success or FileError on a recoverable failure; their result can be captured explicitly.

Byte data is never UTF-8-validated or normalized. Local/remote path names and picker strings use the normal host text boundary: valid UTF-8 normalized to NFC, without NUL. This does not change Wren’s String semantics.

Directory

Opaque handle containing a directory pathname grant. The grant applies to the pathname, not to a particular filesystem object that occupied it when the handle was created.

Method Description

Directory.contains(name)

true for a regular file/subdirectory, false for a missing or unsupported entry, or FileError if the query fails. Symlinks are not followed.

Directory.list

A Map keyed by entry name; values are File objects for regular files and Directory objects for subdirectories. Symlinks, device nodes, FIFOs, etc. are silently skipped. Names are filtered by the policy of the directory’s Cache or Download root. Each read enumerates the directory afresh; cache the value if you’ll touch it more than once. Use this to obtain handles to existing files, or to walk a tree. Returns FileError on failure; never returns a partial Map.

Directory.create(name)

Atomically create a new zero-byte file named name in the directory and return a File object for it. Uses C11 exclusive- create mode (fopen(path, "wbx")) so a concurrent creator doesn’t silently truncate an existing file. Returns FileError for native failures (including IOErr.alreadyExists); invalid names abort. The file is closed on return — call File.open() before reading or writing.

Directory.createDir(name)

Atomically create a new subdirectory named name and return a Directory object for it. Uses mkdir directly, which fails atomically if the path already exists — same race-free semantics as create() for files. Returns FileError on native failure; invalid names abort. Use list[name] to obtain a handle to a subdirectory that already exists.

Directory.delete(name)

Remove the entry named name from the directory. Handles regular files and empty subdirectories; refuses anything else (symlinks, device nodes, FIFOs, non-empty directories). Returns null on success or FileError with the native reason on failure. Invalid names abort.

Directory.replace(name, bytes)

Atomically replace a regular file with the complete byte String. The host writes and closes an exclusive sibling temporary file before the rename, so any write or close failure leaves the prior file unchanged. Returns null on success or a FileError on failure. This operation is intended for cache documents which must never expose a truncate-then-write intermediate state; it does not promise persistence across a system crash.

Pathname grants

File and Directory foreign objects retain an absolute pathname and the operations granted for that pathname. They are not filesystem snapshots and do not preserve the identity of a particular file or directory. A closed handle therefore addresses the current entry at its pathname. Removing, replacing, or recreating that entry does not revoke the grant, whether the change came through Directory.delete or from outside SyncTERM.

Operations validate the state they require. An unavailable pathname returns FileError with the native reason (IOErr.notFound, notDirectory, permissionDenied, etc.); it does not revoke the grant. A recreated directory or file can be used through the same grant. File.path, File.token, and Directory.toString report stored metadata without filesystem access. File.close() is also independent of pathname availability.

Open files are exempt

A File whose stream is currently open (between File.open() and File.close()) performs stream operations on that opened stream and bypasses the closed-path existence check. This matches platform reality:

  • On Unix, an open file descriptor remains valid after the path is unlinked; reads and writes continue to work, and the inode is freed only when the last reference closes.

  • On Windows, deleting a file that’s currently open fails at the OS layer, so the situation never arises.

After File.close(), a later open resolves the pathname again and may open a replacement file. Properties implemented as pathname operations, including mtime and digest(algorithm), continue to resolve the pathname even while a stream is open. Stored metadata properties do not access the filesystem.

Filename Policies

Directories below Cache use the strict portable cache-name policy:

  • Length 1..64 bytes.

  • Characters from [A-Za-z0-9._-] only.

  • Must not begin with . or -.

  • Must not end with ..

  • Must not contain ...

  • Must not match a Windows reserved device name (CON, PRN, AUX, NUL, COM1..COM9, LPT1..LPT9), case-insensitively and with or without an extension.

Directories below Download use the relaxed safe-leaf policy. Names are 1..255 bytes, must not be . or .., and may not contain a path separator, NUL, an ASCII control byte, DEL, or a Windows reserved device basename. Spaces, leading dots or dashes, trailing dots, parentheses, and non-ASCII bytes are otherwise accepted. Descendant directories inherit their root’s policy. Invalid names abort every directory method before filesystem access. Names are validated as UTF-8 and normalized to NFC before the name policy checks and filesystem access.

File

Every File carries rights assigned by the host when it is created:

  • Files reached through Cache or Download are read/write.

  • Files returned by Host.pickFile / Host.pickFiles, or reconstructed by Host.openLocalFile, are read-only. open() uses rb; write methods and mtime=() abort the fiber. Read-consuming bindings such as Screen.loadFont() accept these Files.

  • Files returned by Host.pickSavePath are one-shot write-only grants. Read methods, hashes, and read-consuming bindings reject them. See Write consent.

Permissions apply to the stored pathname, not to a particular file object at that pathname. The foreign handle retains those permissions so a script cannot substitute a different pathname. Passing a File to another binding does not broaden its authority.

Method Description

File.open()

Open the file using the mode authorized by its host-assigned rights. Sandbox Files use r+b, picker/token Files use rb, and save-picker Files use the one-shot mode described below. Subsequent permitted reads / writes start at offset 0.

File.close()

Close the stream; returns null or FileError. Already-closed grants return null. A failed native fclose still consumes the stream and leaves isOpen == false; its error reports any failed flush/close.

File.readBytes(count)

Read up to count bytes from the current offset; advance. Returns a nonempty byte String, null at EOF, or FileError. Zero count returns "" without changing the offset.

File.readBytes(count, offset)

Same results at an absolute offset; restore the current offset even after a successful short read or EOF. Zero count performs no seek.

File.read()

Read file bytes from offset 0, returning "" for an empty file, or FileError. A concurrent truncation can produce a successful short read.

File.writeBytes(s), writeBytes(s, offset)

Write the byte String at the current or given offset. Returns null or FileError. Zero bytes do not change offsets, including explicit offsets.

File.write(s)

Replace file contents with s. On an append-consent File, append s instead so the consent cannot be broadened into overwrite access. Returns null or FileError.

File.truncate(size)

Resize an open writable file to an exact nonnegative integer byte length; see Native integer limits. Shrinking discards the tail; extending fills the added bytes with zero. Preserve the current offset, even beyond the new EOF. Synchronizes buffered input/output first, so later reads cannot return discarded bytes and buffered writes cannot regrow the truncated tail. Zero and unchanged lengths still perform the native operation. Returns null or FileError with the native reason and captured errno. Pending writes may already have flushed when resizing fails; there is no rollback or automatic retry. Invalid lengths, closed/unopened handles, read-only grants and append-only consent abort before I/O. Create/overwrite consent permits resizing during its one-shot open lifetime. No new grant or path access is created. For example: var result = file.truncate(1024).

File.readLine()

Read from the current offset to the first LF (0x0A) or EOF and return the bytes read with LF and its optional preceding CR removed. An unterminated trailing CR is preserved. Advances the offset past the LF on a hit, or to EOF if none was found. Returns null when the offset is already at EOF; a blank line returns the empty string.

File.writeLine(s)

Write s at the current offset, then append an LF (0x0A). The offset advances past the LF. No special handling if s already ends in LF — the trailing LF is appended unconditionally; use writeBytes for raw control over line termination. Returns null or FileError.

File.offset, offset=(o)

Current read/write position. Nonnegative exact integer; see Native integer limits.

File.size

Length in bytes, subject to Native integer limits. Flushes this stream’s buffered writes before querying native metadata; flush failure is a FileError.

File.mtime, mtime=(t)

Signed POSIX seconds within Native integer limits. The setter uses the native filesystem API by path, requires write rights, and works on open and closed handles. Pending output is flushed first. A filesystem which ignores or rounds a timestamp returns IOErr.outOfRange after verification, rather than reporting the requested value as stored. Used by the SFTP queue to stamp completed downloads with the remote’s mtime so the browser’s status chip can compare local-vs-remote without server-side hash extensions.

File.isOpen

true while the underlying stream is open.

File.token

Opaque consent token for picker-sourced File`s; `null for File`s obtained via `Cache / Download Directory listings. Persist this in WON next to the path string and pass back to Host.openLocalFile on resume to re-construct the File at the same absolute path. See "Picker consent tokens" below.

File.digest(algorithm)

Hash the complete file using a Digest algorithm. Returns a raw-byte String, FileError for filesystem failures, or DigestError for native hashing failures. Requires read authority; the stream need not be open. Flushes pending output and maps the stored pathname without changing the logical stream offset or copying file contents into Wren. Empty files hash as the empty buffer. The file must not be concurrently modified, replaced or truncated while mapped. SHA-1 and MD5 results compare directly with SFTPEntry.hash; use byte counts (hash.bytes.count) when interpreting raw hashes. Replaces the v1 sha1 and md5 getters without aliases.

A closed File whose pathname is unavailable returns a FileError with the native reason, such as IOErr.notFound from the existence check, whether the entry was deleted through Directory.delete or outside SyncTERM. The pathname grant remains valid. If a regular file is later created at the same pathname, the original File can open it.

Files minted by Host.pickSavePath carry a write-only consent — a single-shot grant to open the user-picked path exactly once, in a specific mode determined at pick time:

Picker outcome open() mode

Path didn’t exist at pick time

wbx (exclusive create) — fails if the path now exists. Race-safe: an attacker can’t substitute a different file between the picker’s "does it exist?" check and open().

Path existed and the user confirmed overwrite

wb (truncate or create). The picker enforces the prompt; user saying "no" re-prompts.

Path existed and the user selected append

ab (append or create). Every write is placed at the end of the existing file.

The consent is consumed by the first successful open(). After the matching close(), every subsequent open() / writeBytes / write / writeLine / etc. aborts the fiber with "write consent already used". Re-pick the path to write again.

The grant never includes read authority. read, readBytes, readLine, digest(algorithm), and bindings which consume a readable File reject a save-picker File, both before and while it is open.

File.token is null on write-consent Files: persisting a write consent across sessions would defeat the single-shot rule. The existing token mechanism is exclusively for read consent (the Host.pickFiles / openLocalFile upload-resume flow).

Other bindings consume write consent on the caller’s behalf:

After any of these calls the File is inert — calling open() on it yourself is no longer valid.

FileError

FileError represents a recoverable local filesystem failure, following Filesystem results. Its portable code describes the native reason rather than the operation which happened to fail. Existing targets, missing paths, permissions, full storage and native range failures remain distinguishable. The fixed-purpose Emoji.recordUse operation also returns FileError for failure to persist recents; its session update has already occurred and its errno is zero.

Member Description

code

Stable negative native IO_ERROR_* reason, exposed by IOErr below.

errno

Captured C errno when available; zero for native APIs without errno or a synthesized failure. Interpret code for portable decisions.

message

Operation-specific diagnostic text, or null if allocation failed.

toString

Numeric code and diagnostic, plus errno when present.

IOErr exposes all shared native I/O reasons in every script VM. In v2 it replaces FileErr without an alias; FileError remains the filesystem error type:

Constant Code

IOErr.invalidArgument

-1

IOErr.invalidEncoding

-2

IOErr.notFound

-3

IOErr.permissionDenied

-4

IOErr.alreadyExists

-5

IOErr.notDirectory

-6

IOErr.isDirectory

-7

IOErr.directoryNotEmpty

-8

IOErr.outOfMemory

-9

IOErr.noSpace

-10

IOErr.nameTooLong

-11

IOErr.outOfRange

-12

IOErr.busy

-13

IOErr.readOnly

-14

IOErr.crossDevice

-15

IOErr.tooManyLinks

-16

IOErr.interrupted

-17

IOErr.notSupported

-18

IOErr.io

-19

IOErr.timedOut

-20

IOErr.cancelled

-21

IOErr.wouldBlock

-22

IOErr.inProgress

-23

IOErr.nameResolution

-24

IOErr.connectionRefused

-25

IOErr.connectionReset

-26

IOErr.connectionAborted

-27

IOErr.notConnected

-28

IOErr.networkUnreachable

-29

IOErr.hostUnreachable

-30

IOErr.addressInUse

-31

IOErr.addressNotAvailable

-32

IOErr.messageTooLarge

-33

IOErr.protocol

-34

IOErr.passwordRequired

-35

IOErr.decryptionFailed

-36

IOErr.invalidFormat

-37

IOErr.conflict

-38

Success is null, never a zero-code error. EOF is a read result, never a FileError. Programmer errors (wrong types, invalid names/counts/offsets, missing rights, unopened streams, opening an already-open stream) abort; check the input contract rather than treating them as recoverable I/O.

The binding manages C update-stream direction changes and buffered writes. Scripts may mix reads/writes without inserting C-specific seeks or flushes. The current offset remains a logical stream position; metadata queries that need pending output flush it and report any failure normally.

Picker consent tokens

Wren scripts must not synthesize File foreigns from arbitrary paths — that’s the whole point of the Cache / Download sandboxed roots and the relaxed-name predicate. The escape hatch is Host.pickFile / Host.pickFiles, where the isolated picker interaction is the user’s signal of consent.

To let queued picker-sourced uploads survive a disconnect, the picker mints a capability token at consent time: an HMAC-SHA256 binding of the absolute path and the file’s SHA-256, signed by a per-installation key stored in the user’s encrypted syncterm.lst. Wren can store the token freely (it’s opaque bytes — exposed via File.token and accepted by Host.openLocalFile); only the C side can mint or verify one. The file-content hash routes through DeuceSSH’s hardware-accelerated digest backend (Intel SHA-NI / ARM crypto extensions, via OpenSSL or Botan) when the build has it, so signing/verifying a multi-GB picked file stays in the sub-second range on commodity hardware. WITHOUT_DEUCESSH builds fall back to xpdev’s pure-C SHA-256 (src/hash/sha256.c) — correct, just slower on huge files; signing key generation in that build seeds from /dev/urandom (or time/PID) via xp_random rather than the SSH backend’s CSPRNG.

At resume time, Host.openLocalFile(token) verifies:

  1. The HMAC matches (token wasn’t tampered with; signing key hasn’t rotated).

  2. The file at the encoded path still exists.

  3. The file’s current SHA-256 still matches the SHA-256 captured at consent time.

Any failure returns null; the queued upload should be marked failed and the user prompted to re-pick. The content hash binding is deliberate: if the file’s content has changed since consent, the original consent doesn’t authorize uploading the new content.

The signing key is loaded only from the user’s personal BBS list (USER_BBSLIST) — never from shared/system or web-fetched lists. This stops a malicious shared list from injecting a known key and forging tokens against the local install. Key rotation is manual: remove the WrenPickerHmacKey line from syncterm.lst; SyncTERM regenerates on next launch. All in-flight picker tokens become invalid.

Host.pickFile / Host.pickFiles continue to work even when the signing key is unavailable (e.g. an unencrypted list, OOM during generation) — the returned File`s have `null .token, so picker uploads in such sessions don’t persist across reconnects but otherwise behave normally.

Hook

The dispatcher registry. See Hook Events for the contract on each method, and HookHandle for the return type.

Hook.onKey(fn), Hook.onPhysicalKey(fn), Hook.onInput(fn), Hook.onMouse(fn), Hook.every(ms, fn), plus the filtered variants Hook.onKey(key, modifiers, fn), Hook.onInput(byte, fn), Hook.onPhysicalKey(evdev, fn), Hook.onMouse(event, fn), and Hook.onMatch(pattern, fn). Each call returns a HookHandle.

Status

Wren-driven status bar. The host invokes a single render callable on every status-bar update with a width×1 Surface that has been pre-filled to the default attribute (yellow on blue, spaces). The callable mutates cells in place and returns; its return value is ignored.

In RIPv3, the supplied cells use the active RIP text-window font after a text-window font change. Other emulations retain the local status font.

import "syncterm" for Status, Surface, Screen, Session, CTerm

Status.callable = Fn.new { |surf|
  if (!Status.enabled) return
  var s = "%(Session.current.name) | %(Session.current.profile.connTypeName) | %(Session.current.profile.bpsRate) bps"
  var x = 1
  for (ch in s) {
    var columns = Screen.textWidth(ch, surf[0].font)
    if (columns == 0) continue
    if (x + columns > surf.width) break
    surf[x].ch = ch
    x = x + columns
  }
}

In a connected terminal, a left click on an OSC 8 hyperlink activates its actual destination. Ctrl+click also detects plain-text URLs and remains a local action when the BBS has enabled mouse reporting; ordinary clicks then continue to the BBS. A locally activated gesture is consumed through release or drag end so it cannot open twice or send an unmatched mouse release. Opening uses the desktop URL handler for HTTP, HTTPS, FTP, and FTPS. Other schemes, unavailable handlers, and safe mode copy the URI to the clipboard and show a notice unless popups are hidden. These actions are attached to user input and do not grant connected scripts a URL-launch API.

The default implementation lives at scripts/auto/connected/status_default.wren. It uses the layout name (flags) │ ConnType │ speed │ HH:MM:SS │ ALT-Z menu with right-pinned indicators for mouse mode (M) and SFTP transfers (arrows). To override it, place a same-named file in the auto-load directory, or set Status.callable = …​ from any later script. The host releases the previous handle when the callable changes.

Member Description

Status.callable

The currently installed render Fn (or null when nothing has been set). Read it back if you want to chain — wrap the existing callable in your own multi-line Fn.new and call original.call(s) before the additional statements.

Status.callable = fn

Install (or clear) the render callable. fn must be a callable taking one argument (the Surface the host hands it); pass null to detach. Releases the previous handle.

Status.details, Status.details = fn

Optional no-argument callable returning a complete human-readable status String. SyncTERM snapshots it when the disconnect notice appears and shows it in the F1 details popup, so fields omitted by narrow visual layouts remain available. Set it to null to detach it. A custom status renderer should replace both callables when its state differs from the default bar.

Status.hoverUri

The OSC 8 hyperlink destination under the last unclaimed mouse position, or null outside the terminal, while suspended, or over an unlinked cell. The destination is resolved against current screen cells, so a remote redraw cannot leave a stale preview. The default bar centers this URI, truncating with …​, and restores the connection status on leaving it.

Status.enabled

true while the SyncTERM-managed status row is active; false when DECSSDT, the RIPv3 status option or startup config has hidden it. The render callable should early-return on !Status.enabled so it doesn’t do layout work that won’t be displayed.

The recycled Surface is reallocated only when the terminal width changes, so per-frame allocation churn stays out of the hot path. Out-of-bounds writes (surf[i] for i >= surf.width) throw — treat surf.width as authoritative and clip your own loops.

Transfer

Session-owned bridge between the Wren transfer UI and C protocol workers. upload(), uploadBatch() and download() return null after starting a worker, or TransferError if startup fails. The terminal owner continues pumping protocol input while TransferApp renders progress and handles cancellation on a child fiber. Workers never call Wren or CTerm. Only one in-band transfer can own a session’s stream at a time; SFTP uses its separate SSH channel.

import "syncterm" for Transfer
import "transfer_app" for TransferApp

Fiber.new {
  var error = Transfer.beginSession("fake")
  if (error != null) Fiber.abort(error)
  TransferApp.new("Transfer demo").run()
  var result = Transfer.result
  Transfer.endSession()
  if (result != null) System.print(result)
}.call()

The built-in upload/download flows are available through Alt-U, Alt-D and the online menu. ZMODEM auto-start watches the incoming bytes for Ctrl-X followed by B00 (download) or B01 (upload). Each byte reaches normal terminal processing as it arrives. The transfer engine checks the complete header CRC. Downloads use the configured download directory; unsafe roots and existing non-file destinations are rejected. If the configured directory is unavailable, the connected UI shows a notice with the Download Path setting to change. The detector checks the directory on each request and groups retries less than 30 seconds apart into one notice. Existing files can be overwritten, skipped, or renamed. ZMODEM resumes a partial file only after checking its prefix CRC against the sender.

For a DDO F/X entry, a completed ZMODEM download batch installs recognized $LI$ command packages in that BBS’s DDOFX cache before the session resumes. Installation errors go to the transfer log. Ordinary downloads retain their chosen destination.

RIP block-transfer commands use that BBS’s RIP cache subdirectory instead of the download directory. RIP 1.54 display-only and active dynamic modes render validated blocks as they arrive, using status-row progress so a modal restore cannot erase the scene. RIPv3 displays successfully received scenes and images after the transfer returns, using the active RIP3 style and parser. A failed RIPv3 receive removes the incomplete destination. Earlier completed files in the batch retain their own completion results. Host-requested uploads always require confirmation and read regular files in the BBS cache. RIP 1.54 accepts one filename per upload. RIPv3 batch uploads can name several files. RIP transfers use the same cancellation, completion and log APIs as manual transfers.

Member Description

Transfer.beginSession(kind)

Start the synthetic 100-KiB "fake" worker for UI testing. Use the protocol dispatch methods below for real transfers. Returns null or TransferError (including IOErr.busy when already active). An unknown kind aborts as programmer misuse. Synthetic work remains available in safe mode.

Transfer.endSession()

Latch an abort if the worker hasn’t already finished, join the thread, and clear session state. Idempotent — safe to call after a natural completion. Returns null.

Transfer.drainLog()

Drain the log ring under mutex; return a List of [level, text] entries. When the ring overflowed since the last drain, a synthesized [LOG_NOTICE, "[N log lines suppressed]"] marker is appended at the tail so the suppression is visible to the user. Empty list when no events pending.

Transfer.tickDirty

Read the "tick state changed" flag under the mailbox mutex. snapshot() clears it. Returns true if a tick update has happened since the previous call; callers should follow with snapshot() only on a true return so the mutex is taken at most once per dirty frame.

Transfer.snapshot()

Return [line1, line2, line3, line4, bytesCurrent, bytesTotal]. The first four elements are display Strings. Byte counts are Numbers; an unknown total is zero. Clears the dirty flag. TickStateView in transfer_app provides named accessors.

Transfer.done

true when the worker has completed (success or abort). The pump loop exits on this flag.

Transfer.result

Read-only completion result: null for success or TransferError preserving the native failure code. Requires active && done; other reads abort as programmer misuse. Reading does not clear progress, drain logs, join or release the worker. A captured error remains usable after endSession() and subsequent transfers. The former success getter is removed without an alias.

Transfer.requestAbort()

Latch an abort flag the worker polls between protocol steps. Returns true only on the first call (the latch transition), letting callers post a one-shot "Abort key pressed" log line without spamming on key-mash.

Transfer.aborted

Read the abort flag without modifying it. true after a successful requestAbort(). This is the local request latch; a peer can cancel with result code IOErr.cancelled while this flag remains false.

Transfer.active, Transfer.uploading, Transfer.inlineUpload, Transfer.inlineProgress

Whether a session owns a transfer and its direction. inlineUpload marks ASCII/raw uploads; inlineProgress also includes RIP downloads that display scenes while receiving. An active transfer retains its result until endSession().

Transfer.upload(kind, source, lastCh)

Start one file using "zmodem", "ymodem", "xmodem-1k", "xmodem-128", "ascii", or "raw". source is a readable File belonging to the calling VM, normally returned by the picker. A write-only save grant is rejected. A path String is also accepted for an existing regular file inside the current BBS’s cache or configured upload directory, including subdirectories. Paths validate as UTF-8 and normalize to NFC; normalized paths outside those roots and descendant symlinks/reparse points are rejected. Other locations require a File grant; converting one to .path or .toString does not retain its authority. lastCh is normally zero; an already-consumed X/YMODEM C, G, or NAK can seed the initial handshake. ASCII normalizes LF to CRLF; raw preserves bytes.

Transfer.uploadBatch(kind, sources, lastCh)

Start a List of readable File grants or exempt path Strings using "zmodem" or "ymodem". Every element is validated before any worker starts; a rejected element rejects the entire batch.

Transfer.download(kind, filename)

Start "zmodem", "ymodem-g", "ymodem", "xmodem-g", "xmodem-crc", "xmodem-chksum", or "cet". XMODEM requires a filename and keeps final-block padding because its wire format carries no length. Other kinds accept null. CET requires Prestel mode and starts from the captured current frame; its final frame is replayed on the terminal owner. XMODEM-G streams without per-block acknowledgments or retries. It is a download choice; the existing XMODEM upload modes negotiate G-mode with the receiver.

Transfer.dialogPending, Transfer.dialogFilename

Pending worker decision: 0 for none, 1 for an existing file, 2 for an XMODEM filename when a YMODEM receive falls back to XMODEM.

Transfer.dialogRespond(response, newName)

Answer a pending decision with 0 (overwrite/accept filename), 1 (skip), or 2 (rename). The worker waits on a condition variable while the owner continues pumping. Abort and disconnect also wake that wait.

All startup methods return null or TransferError; they do not wait for completion. Wrong argument types, malformed UTF-8, embedded NUL in protocol tokens or required download filenames, unsupported protocol/direction, invalid handshake bytes and invalid upload grants abort as programmer misuse. Host text normalizes to NFC; raw file bytes do not. Native filename validation remains authoritative. Runtime restrictions and download roots are unchanged: real transfers require a permitted connected session, and safe mode blocks them. The internal RIP-upload acceptance method also returns null/TransferError; no pending request is misuse.

The bundled progress App derives its success convenience property from the completion result, retains its local aborted property and displays the actual failure message or cancellation. Inline flows capture the result before cleanup. Startup failures display once and do not enter the progress UI. Existing cleanup and partial-file behavior remain; an error is not a guarantee of rollback or a safe offset from which to retry automatically. The detailed transfer log remains separate from the result.

TransferError

An immutable Error value, available with Transfer in each VM. It owns its diagnostic and retains no worker or session pointer. There is no public constructor.

Member Description

code

The exact native portable I/O integer; compare with IOErr constants. Unknown native integers are preserved. Success is represented by null.

message

Nonempty human-readable startup or completion diagnostic. Detailed per-file/protocol diagnostics remain in the transfer log.

toString

Includes TransferError, the numeric code and the message; meant for display, not parsing.

Platform

OS identification and preferred UI languages. No shell execution, stdio, or process model is exposed.

Method Description

Platform.name

OS identifier as a String. Returns "Windows" on Windows; the uname(2) sysname field on POSIX hosts (typically "FreeBSD", "Linux", "Darwin", etc.); "Unknown" on anything else. Win32 is checked before POSIX, so Cygwin / MSYS report the native OS.

Platform.languages

Fresh, nonempty List of unique language-tag Strings in preference order, such as ["fr-CA", "en"] or ["zh-Hant-TW"]. Windows uses the user’s preferred UI languages (falling back to their default UI language); macOS uses its preferred language list. Other POSIX hosts use LANGUAGE’s colon-separated message preferences, with the effective message locale chosen from nonempty `LC_ALL, LC_MESSAGES, then LANG. LANGUAGE is ignored for C, POSIX, and their encoding-qualified forms. Missing or unusable preferences default to ["en"]. POSIX encoding suffixes are removed and underscores become hyphens; @latin, @cyrillic, and @valencia retain their script/variant meaning. Other modifiers are ignored. Tags have conventional language/script/region casing; this is not a full CLDR alias or translation-fallback resolver. Discovery does not call setlocale() or change connection encoding. Available in connected, menu, and picker VMs; allocation failure aborts the calling fiber. This API discovers preferences; it does not translate UI.

Digest

Stateless synchronous hashing, available in menu, picker and connected VMs. Digest.hash consumes bytes already in a Wren String; File.digest separately uses a native file mapping and requires a readable File grant. Byte hashing provides no filesystem authority.

Algorithm constant Native value / output bytes

Digest.sha256

1 / 32

Digest.sha384

2 / 48

Digest.sha512

3 / 64

Digest.md5

4 / 16

Digest.sha1

5 / 20

Digest.size(algorithm) returns the output byte length even when the selected provider cannot compute that algorithm. It is not an availability query. Digest.hash(algorithm, bytes) returns the raw digest bytes as a String or a DigestError. Every input byte participates, including NUL and malformed UTF-8; no text validation or normalization occurs. Canonically equivalent Unicode spellings can therefore have different hashes. Compare raw results directly, and use .bytes.count for their lengths.

import "syncterm" for Digest, Error
var hash = Digest.hash(Digest.sha256, "abc")
if (hash is Error) Fiber.abort(hash)
System.print(hash.bytes.count) // 32

Wrong input types, fractional/nonfinite numbers and unknown algorithm constants abort the fiber before hashing or file effects. Byte-String input must also fit the Wren C byte API’s signed-int length range; this limit does not constrain native mapped-file input. Known algorithms whose native operation fails return DigestError; no availability preflight or automatic retry is performed. Builds with provider none support MD5 and SHA-256. SHA-1, SHA-384 and SHA-512 return the native disabled status in those builds. External providers can also fail according to their native policy; those failures are not relabelled as disabled.

DigestError

Host-created, immutable Error subclass with read-only code, message, and toString. code is the exact nonzero native digest status, including an unrecognized future status. message identifies Digest.hash or File.digest and describes the native reason; toString also includes the code. Success returns bytes, never a zero-code error. DigestErr.failed (-1) names the generic native failure; DigestErr.disabled (-5) names disabled digest support.

File.digest retains FileError for pathname, flush and mapping failures, and returns DigestError for failures from the native hashing operation. Check the common Error base if either is relevant. A pending-write flush can succeed before hashing fails; no partial digest is returned. Input is borrowed only for the synchronous native call, mappings are released before return, and returned Strings and errors remain valid through later calls and garbage collection.

Text

Locale-independent Unicode 18 comparison helpers. All inputs are normalized to NFC at the Wren host boundary. Caseless matching uses full default Unicode case folding with canonical equivalence; ordering uses the non-ignorable DUCET collation table and an identical tie-break for deterministic results.

Method Description

Text.graphemes(text)

Return a List of NFC extended grapheme cluster Strings using the shared Unicode text engine. Used by UI drawing so joined emoji resolve as one glyph.

Text.normalizedByteCount(text)

Return the UTF-8 byte count after NFC normalization. Use this when checking input against byte limits on C-backed text fields.

Text.caselessKey(text)

Return the NFD full-default-casefold key used by caseless equality. This is useful for retained search prefilters; use the matching methods below to verify a candidate when grapheme-cluster boundaries matter.

Text.caselessEqual(left, right)

Canonical caseless equality.

Text.caselessStartsWith(text, prefix)

Caseless prefix matching at extended grapheme-cluster boundaries.

Text.caselessContains(text, needle)

Caseless substring matching at extended grapheme-cluster boundaries.

Text.compare(left, right, caseSensitive)

Return a negative number, zero, or a positive number using Unicode 18 DUCET ordering. The Boolean selects tertiary (case-sensitive) rather than secondary (case-insensitive) strength.

Timer

Timers are connected-session operations. Timer.after(ms) returns an Operation that completes with null after the delay. The delay must be an integer from 0 through 4294967295 milliseconds. Invalid arguments, allocation failure, and exceeding the 32 pending timers per VM abort the calling fiber. Cancellation removes the timer immediately and frees its slot. A zero delay completes on the next owner-loop pump, never inside after.

Timer.now returns monotonic seconds as a Num; only differences between readings are meaningful. For recurring callbacks, use Hook.every(ms, fn).

import "syncterm" for Timer

var delay = Timer.after(250)
var result = delay.await()
// result is null, or OperationError if another owner cancelled the delay

Format

Number-to-string helpers for human-readable display. Both methods auto-pick a unit based on the magnitude of the input and use one decimal of precision; negative inputs are clamped to zero.

Method Description

Format.bytes(n)

Format n bytes as a String with a K / M / G / T / P suffix (e.g. "1.4M", "100.0K", "42"). Uses 1024-byte units. Throws if n is not a Number.

Format.duration(seconds)

Format seconds as a String with a s / m / h / d / y suffix (e.g. "8.2s", "1.5m", "3.0h"). Throws if the argument is not a Number.

Combined idiom — display a transfer rate and ETA:

import "syncterm" for Format, Timer

var startedAt  = Timer.now
var startBytes = job.done
// ... later ...
var elapsed = Timer.now - startedAt
var moved   = job.done - startBytes
if (elapsed > 0) {
  System.print("%(Format.bytes(moved / elapsed))/s")
  var remain = job.total - job.done
  if (remain > 0) {
    System.print("ETA %(Format.duration(remain / (moved / elapsed)))")
  }
}

SFTP

SSH-channel side-band file transfer. Each operation queues work on the connection-owned SFTP worker and returns an Operation. Both immediate and deferred recoverable failures are SFTPError result values; .await() obtains the result in either case. Arguments of the wrong type abort the calling fiber before work is submitted. Up to 256 provider requests may be outstanding; a full queue returns a completed operation with an SFTPError rather than accepting unbounded work.

Method Description

SFTP.start()

Lazily open and negotiate the SSH SFTP subsystem. Completes with true or SFTPError through its operation result. Concurrent calls share one negotiation, and calls after success do not open another channel. A failed startup is retained until reconnect. Call before other operations. Non-SSH connections complete with SFTPError.

SFTP.available

true while the SSH connection has a negotiated, usable SFTP subsystem. This getter, pubdir, and lname never start negotiation. An idle SSH session opens no SFTP channel; the browser, pending transfer work, or enabled public-key installer requests startup when needed. Viewing an empty transfer queue does not negotiate SFTP. The entry’s SFTP Public Key toggle controls only automatic key installation, not interactive SFTP.

SFTP.pubdir

The remote pubdir@syncterm.net path advertised by the server, or null if the extension wasn’t negotiated.

SFTP.lname

true when the session negotiated the lname@syncterm.net extension — the per-entry friendly long name (directories) / short description (files) that SFTPEntry.longname carries. UI code can use this to decide whether to reserve a row for a description bar that would otherwise always be blank.

SFTP.realpath(path)

Resolve path to an absolute server path. Completes with String or SFTPError.

SFTP.stat(path)

Stat a remote path. Completes with SFTPStat or SFTPError.

SFTP.opendir(path)

Open a directory cursor. Completes with RemoteDirectory or SFTPError.

SFTP.open(path, flags)

Open a file with explicit rights. Completes with RemoteFile or SFTPError. flags is a bitmask from FileFlag below. At least one of read/write is required. Append/create/truncate/exclusive require write; exclusive also requires create. Unknown bits and inconsistent flags abort before submission.

SFTP.mkdir(path), SFTP.rmdir(path), SFTP.remove(path), SFTP.rename(oldpath, newpath)

Mutation ops. Each completes with null on success or SFTPError.

SFTP.setMtime(path, t)

Set both atime and mtime of path to t (POSIX seconds). Used by the upload queue to stamp completed remotes with the local file’s mtime so a subsequent browse shows [==] without depending on hash extensions. Completes with null on success or SFTPError (e.g. read-only mount).

SFTP.descs(path)

Fetch the server’s long description for path via the descs@syncterm.net extension. Completes with the description String (possibly empty) or SFTPError, including when the server does not support the extension. SFTPEntry.hasLongDesc is a per-entry hint — server-asserted presence — that lets browsers decide whether to mark a row as having a long description available without paying the round-trip cost on every selection.

FileFlag

OR-able bitmask constants for SFTP.open’s flags argument; each matches the corresponding `SSH_FXF_* wire constant.

Constant Wire value

FileFlag.read

0x01

FileFlag.write

0x02

FileFlag.append

0x04

FileFlag.creat

0x08

FileFlag.trunc

0x10

FileFlag.excl

0x20

SFTPEntry

One entry from RemoteDirectory.readEntries.

Member Description

name

Filename relative to the parent directory.

longname

Server-formatted long name (when the lname@syncterm.net extension was negotiated; null otherwise). For directories this is the friendly long name (UI label); for files it’s the one-line short description (UI status bar).

stat

A fresh, immutable SFTPStat copy of this entry’s listing metadata.

isDir

true if the entry is a directory.

hasLongDesc

true if the server marked this entry as having a long description available via the descs@syncterm.net extension. Lets browsers show a "+" marker on rows with descriptions without paying the round-trip cost; fetch the actual text with SFTP.descs(path).

hash

SHA-1 / MD5 digest bytes from sha1s@syncterm.net / md5s@syncterm.net, or null if neither extension was negotiated. Compares directly against file.digest(Digest.sha1) / file.digest(Digest.md5).

SFTPStat

Result of SFTP.stat, or the metadata returned by SFTPEntry.stat. All members are read-only; there is no public constructor. Size and timestamps follow Native integer limits; mode, UID and GID retain their unsigned 32-bit values. Attributes omitted by the server retain the native API’s zero defaults.

entry.stat constructs its native metadata copy only when accessed. Each access returns a new object holding the metadata from the directory listing, without issuing a request or refreshing it. The copy survives directory closure, entry collection and later responses. It grants no remote-resource authority. For current metadata, explicitly await SFTP.stat(path) instead.

In v2, SFTPEntry.size and SFTPEntry.mtime are removed. Use entry.stat.size and entry.stat.mtime, or capture var metadata = entry.stat once when reading several fields. Inexact size or timestamps in any listing entry fail the entire listing Operation with a non-transient SFTPError.

Member Description

size

File size in bytes.

mtime

Modification time, POSIX seconds.

atime

Access time, POSIX seconds.

mode

SFTP-wire permission bits (Unix-style on POSIX servers).

uid

Owner user ID.

gid

Owner group ID.

RemoteFile and RemoteDirectory

These host-created objects own a remote resource in one connected VM. They have no public constructor and cannot be used in another session. The SFTP namespace owns path operations; resource operations belong to these objects.

Member Description

RemoteFile.readBytes(count, offset)

Read at an absolute offset. Returns an Operation completing with a nonempty byte String, null at EOF, or SFTPError. Zero count completes immediately with "". Requires read rights. Independent reads/writes may run concurrently because their offsets are explicit.

RemoteFile.writeBytes(bytes, offset)

Write a byte String at an absolute offset; Operation completes with null or SFTPError. Requires write rights and an open without append mode. The argument order matches local File.writeBytes(bytes, offset). At most 262,123 bytes fit one native write; larger Strings abort before submission. Zero bytes complete immediately with null.

RemoteFile.appendBytes(bytes)

Append a byte String using the server’s current end of file. Requires an open with write and append flags; no misleading offset argument is accepted. The same native write-size limit and zero-byte result apply.

RemoteFile.readable, writable, append

The rights and append mode granted by the successful open.

RemoteDirectory.readEntries()

Read the next directory batch. Operation completes with List<SFTPEntry>, null at EOF, or SFTPError. A second pending cursor read completes with a busy SFTPError; await the first before reading another batch. An empty native batch is normalized to EOF. Malformed provider payloads fail with a non-transient protocol error instead of producing partial data.

resource.close()

Returns an Operation completing with null or SFTPError. Concurrent closes share one Operation and submit one native close. A successful close is idempotent; repeated close completes immediately without native work. Failed close keeps ownership and permits retry. Close while reads/writes remain pending completes with a busy SFTPError; await those operations first.

resource.isClosing, isClosed

Explicit resource state. Reads/writes after close starts abort. Cancelling a close Operation does not revoke the submitted native close: the object remains closing until the provider reply establishes success or failure.

resource.use(fn)

Run fn(resource) in a cleanup scope. Returns its result and awaits close on normal return or abort, including cooperative yields. Close failure aborts with its SFTPError; an original callback error takes precedence. The callback must await any I/O it starts before returning.

Pending native operations retain their receiver, even after cancellation, until their replies are drained. Collecting an abandoned open resource submits a best-effort close and tracks its reply as auxiliary work. GC is a fallback; use an explicit close or scope when completion matters. VM shutdown cancels pending work, marks every resource closed and releases ownership without resuming parked user callbacks. Shutdown cleanup never waits on the network. The browser and public-key installer use scopes; the parallel transfer queue awaits its workers before closing each resource explicitly.

var file = SFTP.open(path, FileFlag.read).await()
if (file is SFTPError) return file
return file.use(Fn.new {|source| source.readBytes(4096, 0).await() })

SFTPError

Returned in place of the typed result on any failure. Two error layers — distinguish via code:

Member Description

code

sftp_err_code_t enum value. Non-zero means a library / transport-level failure (OOM, ABORTED, SEND_FAILED, …); zero means the server returned a STATUS reply with an error code, in which case serverStatus carries it. Negative IO_ERROR_* values identify host/provider-boundary failures before or outside a protocol reply.

serverStatus

SSH_FX_* wire status (e.g. SSH_FX_NO_SUCH_FILE, SSH_FX_PERMISSION_DENIED). Meaningful only when code == 0.

message

Human-readable diagnostic text accumulated by the library (may be null).

isTransient

true for failures that may succeed on retry (transport drops, aborts, OOM).

The toString override produces "SFTPError: <name>: <message>" for System.print / interpolation; useful for log-line debug.

Persistent transfer queue

The shipped sftp_queue module runs one cooperative worker fiber per direction. Jobs have stable numeric IDs; the browser and queue UI retain selection and cancel the intended job by ID even when status sorting changes. Duplicate pending jobs with the same direction and remote path reuse the existing job.

Each claimed interval is filled completely, including when a successful remote or local read returns fewer bytes than requested. Parallel interval completion advances a persisted resume point only across the contiguous prefix of the file, so data beyond a gap is never treated as durable progress. Downloads stat the remote before resuming and restart from zero when its size or mtime changed. Uploads revalidate the picker consent token and fail when the local source changed; a compatible remote partial resumes from the saved frontier.

The queue stores only queued and active work in Cache/sftp_queue.won. Schema version 2 records the next stable job ID, source identity, cancellation request, and contiguous resume point. Version 1 documents are imported conservatively with resume set to zero. Malformed or unsupported documents make the queue unavailable without rewriting the file. Every mutation uses Directory.replace, so a failed persistence write leaves the previous complete document in place and makes the live queue fatal rather than continuing with state that cannot survive disconnect.

Ordinary transfer failures retain partial data for diagnosis or a later explicit retry. A user cancellation removes the local download partial or remote upload partial before publishing cancelled; a transient transport failure suspends the queue and preserves that cleanup request for the next connected VM. Local and remote close failures affect the final job status. Best-effort mtime updates do not turn an otherwise complete transfer into a failure.

Async Ops

Operation

SFTP, timers, and connection sends return an owned Operation for each request. No caller supplies a target fiber, and immediate errors follow the same result contract as asynchronous completion. Operations have object identity, so overlapping requests remain distinguishable even when their result types are identical.

Member Description

isDone

Bool indicating completion, including cancellation.

cancelled

Bool indicating explicit or abandoned-owner cancellation.

result

Completed value or typed Error; aborts before completion.

await()

Obtain the result, parking only when necessary. Multiple fibers may await the same operation; each receives the same retained result.

then(fn)

Run fn(result) in a child fiber on completion and return the operation. An already completed operation invokes the callback immediately.

cancel()

Return true on cancellation, false if already complete. The result becomes an OperationError describing cancellation.

var left = SFTP.stat("/a")
var right = SFTP.stat("/b")
var a = left.await()
var b = right.await()
// Either provider reply may arrive first; identity selects the right result.

SFTP.realpath(".").then(Fn.new {|result|
  if (result is Error) System.print(result.message)
  else System.print(result)
})

Await registers the calling fiber with that specific operation. The owner loop delivers an operation notification to resume it. Unrelated Wake.post messages remain queued in arrival order until the operation wait completes; they cannot substitute for the result. Use .await() rather than a raw Fiber.yield() when waiting for an operation. A direct await in an App handler postpones that handler’s UI events; App.runChild keeps dispatching those events while its child waits.

Pending native work retains its operation even if the script drops the handle. Dropping a handle alone does not cancel the request. Dead or aborted awaiters are pruned at the next pump; when the last awaiting owner dies, its pending operation is cancelled. Completed result storage is released when its operation is collected. VM shutdown cancels pending operations before running disconnect hooks, then releases all roots and waiters without resuming asynchronous script code after teardown.

Timer cancellation removes the native timer. SFTP cancellation abandons the script’s interest in the reply; the provider may already have performed a remote side effect, and cancellation does not roll it back. Late replies are discarded, and late open results receive a best-effort close. A cancelled request ID continues counting toward the provider limit until its reply is drained. Explicitly close successful SFTP handles when finished.

OperationError inherits Error and exposes code, message, and toString. Programming errors, including an invalid private await target or non-Fn callback, abort the calling fiber rather than becoming result values.

WON

The Wren Object Notation — round-trip serialisation between Wren values and a textual literal format. Output is a strict subset of valid Wren syntax (and therefore also pasteable into Wren source). Deserialisation runs a hardened C parser, not eval, so feeding untrusted text to WON.deserialize cannot execute code.

Supported types:

Type Notes

Null

null

Bool

true / false

Num

Num.toString form; NaN / Infinity have no Wren literal and are rejected

String

quoted with Wren-style escapes; % is always escaped to \% so output never starts an interpolation

List

[a, b, c]

Map

{key: value, …​} — keys must be hashable Wren types (Bool, Num, String, Range, null)

Range

coerced to List via .toList; serialisation is one-way (the deserialised value is a List)

Sequence

any other Sequence coerces to List via .toList

Values of any other type abort serialisation in strict mode and are silently omitted (or replaced with null at the top level) in lossy mode. Cyclic Lists / Maps abort in both modes.

Member Description

WON.serialize(value)

Strict compact form. [1,2,3] / {"a":1,"b":2}. Aborts the fiber on unsupported types, NaN/Infinity, or cycles.

WON.serialize(value, indent)

Strict pretty-printed form. indent is a String inserted once per nesting level (e.g. " " for two-space, "\t" for tab). Same error behaviour as the one-arg form.

WON.serializeLossy(value)

Compact form that silently omits unsupported items from Lists and Maps; a top-level unsupported value becomes "null". Cycles still abort.

WON.serializeLossy(value, indent)

Pretty-printed lossy form.

WON.deserialize(text)

Parse text and return the reconstructed value. On parse failure returns a WONError IN PLACE of the parsed value (the fiber is NOT aborted — WON.deserialize is the prototypical consumer of untrusted input, and a corrupt config file shouldn’t kill the script). Tolerates arbitrary whitespace and trailing commas inside […​] / {…​}. Accepts exactly the string-escape set the Wren compiler itself recognises. Programmer errors (passing a non-String) DO still abort.

WONError

Returned IN PLACE of the parsed value when WON.deserialize fails. The script demuxes via is WONError. Mirrors the SFTPError / FileError / ConnError shape.

Member Description

code

WONErr.* enum value.

offset

Byte offset where the error was detected. Useful for flagging a position in the input.

message

Human-readable diagnostic, may be null.

toString

"WONError: <CODE-NAME>: <message> at offset <n>".

WONErr constants:

Constant Code When emitted

WONErr.ok

0

Sentinel; never appears on a returned WONError.

WONErr.syntax

1

Expected token / unexpected character / malformed number.

WONErr.truncated

2

Unterminated string, premature end of input.

WONErr.invalidEscape

3

Malformed \x / \u / \U escape, or unknown \x letter.

WONErr.invalidKey

4

A List or Map was used as a Map key.

WONErr.tooDeep

5

Nesting exceeded the parser’s recursion budget (256 levels).

WONErr.trailingData

6

A complete value was followed by more (non-whitespace) data.

OOM during parsing aborts the fiber (no recoverable path — the parser can’t allocate a WONError to return either).

import "syncterm" for WON

var data = {
  "name":  "syncterm",
  "items": [1, 2, [3, 4]],
  "flags": {"verbose": true, "depth": 7},
}

System.print(WON.serialize(data))
// {"name":"syncterm","items":[1,2,[3,4]],"flags":{"verbose":true,"depth":7}}

System.print(WON.serialize(data, "  "))
// {
//   "name": "syncterm",
//   "items": [
//     1,
//     2,
//     [
//       3,
//       4
//     ]
//   ],
//   "flags": {
//     "verbose": true,
//     "depth": 7
//   }
// }

var roundTripped = WON.deserialize(WON.serialize(data))
System.print(roundTripped["flags"]["depth"])     // 7

// Lossy mode skips unsupported entries instead of aborting.
var mixed = [1, Fiber.new {}, 2, Fiber.new {}, 3]
System.print(WON.serializeLossy(mixed))          // [1,2,3]

Built-in UI Library

SyncTERM ships a pure-Wren widget library on top of the Modal Input primitive. It reuses mutable Cell views while drawing into Surfaces, avoiding a new Wren object for every cell. Drawing still uses foreign cell and text-width methods. The library composites through a screen-sized backbuffer and applies a final Screen.putRect per frame, so the whole thing runs without flicker even on slow remote BBSes. The visual style follows SyncTERM’s classic conventions: cyan-on-blue dialog frames, yellow titles, lightbar selection, drop shadows on modals, and a distinct cyan inactive palette for any pane that’s currently behind a modal.

A minimal session looks like:

import "ui" for App, Pane, ListView, Alert, Rect
import "syncterm" for Screen

var snap = Screen.save()

var app  = App.new()
var size = Screen.size
var pane = Pane.new()
pane.bounds  = Rect.new(2, 2, size[0] - 2, size[1] - 2)
pane.title   = "Pick one"
pane.focused = true
pane.onClose = Fn.new { app.quit() }
app.root.add(pane)

var list = ListView.new()
var ib   = pane.innerBounds
list.bounds = Rect.new(ib.x, ib.y, ib.w, ib.h)
list.items  = ["alpha", "beta", "gamma"]
list.onSelect = Fn.new {|i, item| Alert.show(app, "Picked: %(item)") }
pane.add(list)

app.runSync()
Screen.restore(snap)

App.run() and App.runSync() differ in how they pump events. run() parks a fiber on Fiber.yield() between events — claim handler posts each accepted event via Wake.post, the result queue resumes the fiber. Inbound bytes flow normally, Hook.every and Timer.after keep firing. runSync() blocks the VM on Input.next() instead; use it from contexts where doterm can’t dispatch back into the App, e.g. the Wren console (whose REPL itself runs inside a Hook.onKey).

runSync() dispatches each key or mouse event in a child fiber. A runtime abort from a synchronous handler therefore does not unwind the App’s event loop. By default the App writes the error and trace to the current VM’s console log; set app.onError = Fn.new {|failedFiber| …​ } to replace that reporting. Layout and painting remain outside this boundary so a deterministic redraw failure is not retried forever. Modal frames pushed by a failed event are discarded before error reporting, so an orphaned dialog cannot consume the next Escape or Backspace. A modal that the handler dismissed before aborting remains dismissed.

Key.quit is reserved for the host’s sticky process-close request. App claims it before ordinary widget or global-keymap dispatch. With a modal open, the App sends that modal an Escape for normal cleanup and then removes it if it did not close itself; subsequent pump iterations unwind the remaining Wren call stack. With no modal, the App stops. A widget whose atExit property is true is the explicit exception: it remains interactive while the quit latch is set, and modals it opens inherit atExit. Use this only for work that must finish or be decided during shutdown, such as a save confirmation. The connected-session host handles a real process-close request before dispatching to the connected VM, so remotely supplied scripts cannot use atExit to delay termination.

Importing

Every public class is exported from individual ui_*.wren modules and re-exported from the convenience aggregator ui:

import "ui" for App, Pane, ListView, TextInput, SelectOnFocusInput, Button,
               Checkbox, RadioGroup, SpinBox, DatePicker, CalendarDate,
               MenuBar, StatusBar,
               Form, Alert, Confirm, Prompt, Find, Help, PopStatus,
               Painter, Style, Theme, Glyphs,
               Widget, Container, Rect

If you only need a couple of classes, the per-topic modules cut load cost: import "ui_pane" for Pane, import "ui_popup" for Confirm, etc. They’re listed in UI Modules.

App

App is the root of a UI session. It owns:

  • root — a Container that hosts the foreground widget tree.

  • a modal stack — synchronous dialogs push themselves onto it via app.modal(widget), which blocks until the widget pops itself (typically from its own dismissWith_(value) helper).

  • a global keymap — app.bind(key, modifiers, fn) registers a hotkey that fires when no widget consumes the key. The overload without modifiers uses zero; unbind and binding accept the same optional mask. F1 is bound by default to showHelp.

  • a Theme initialized from Theme.current, which decodes the C-owned active theme and refreshes its per-VM cache when Host.themeGeneration changes. The menu, picker, and connected VMs therefore use the same selected theme. Assign app.theme only when the App intentionally needs a different per-App theme. Assignment invalidates the complete root, transient-status, and modal widget trees so every mounted widget repaints on the next draw.

  • a single run-fiber that pumps the event loop. run() pushes an input claim (see Modal Input) whose handler decides synchronously, from App state alone, whether each event is "for the App" — modal up consumes everything; with a focused widget, keys are claimed and mouse events are claimed when they hit the visible widget tree (or start a drag, which the App owns for rectangular select); otherwise the event falls through to lower claims and then to registered Hook.onKey / Hook.onMouse. Claimed events are delivered to the run-fiber via Wake.post; the next drainOnce_ iteration picks them up and dispatches into the widget tree.

  • a backbuffer Surface sized to the term area (Screen.size minus one row when CTerm.statusDisplay > 0, so the App’s blit doesn’t overwrite the SyncTERM status bar) and a one-shot screen capture (Screen.readRect) used as the backdrop behind everything. Areas not covered by widgets show that capture rather than a styled fill.

Methods of interest:

  • run() / runSync() — enter the event loop in a cleanup scope. Mouse subscriptions, cursor shape and position, and text attributes are restored after normal return, a callback error, or VM shutdown. The input claim and timers are released and running becomes false. Re-entering an active App is an error; a stopped App can run again. tickMs= schedules a periodic onTick_ callback (overridable; no-op by default). Only one tick timer is pending at a time; input and external posts do not accumulate additional timers. runSync() contains runtime errors raised by key and mouse handlers as described above. Errors from layout, painting, ticks, or an error reporter propagate after cleanup, retaining the original error object.

  • onError=(fn) — replace runSync()’s default reporting for a failed event handler. The callback receives the failed `Fiber, whose error and stackTrace describe the abort.

  • quit() — break out of the loop. Widgets and global handlers call this from their key/mouse handlers.

  • modal(widget) — push a modal, drain events until it pops or the App stops, then return the widget so the caller can read its result. A modal whose closesOnOutsideClick(event) method accepts a mouse event receives an Escape when that event occurs outside its bounds. List-style popups accept button 1 and right-click; Help accepts any ordinary mouse-button click. Text prompts and specialized editors reject outside clicks.

  • popStatus(message) — show or clear a transient centered overlay that does not intercept input. Useful for "Working…​" status while blocking on Input.next or a long Wren computation. The overlay sits above the foreground widget tree but below the modal stack, so a dialog the user is actively working with isn’t obscured by an indicator behind it.

  • releaseFocus() / restoreFocus() — wrap a picker call, where another VM temporarily owns the screen, so the App’s foreground tree doesn’t also draw as focused. Without this, the picker host’s pre-call screen save captures the App’s panes in their focused colour scheme, and the post-call restore re-paints them that way until the next App-driven repaint — visually, two widgets are focused at once. Operates on modalTop (so a release while a modal is up defocuses the modal’s leaf, not the root’s) and forces an immediate paint so the unfocused state lands on screen before the host UI saves it. Both are idempotent: a second releaseFocus before restoreFocus is a no-op, and restoreFocus without a prior release is a no-op.

  • invalidateCursorState() — call after a host operation changes conio’s cursor directly. The next draw reapplies the shape, visibility, and colour requested by the focused widget instead of trusting the App’s cached state.

    releaseFocus()
    var picked = Host.pickFiles(Host.uploadPath, "*", 0)
    restoreFocus()
  • showHelp() — walks from the focused leaf up the parent chain to the first widget with helpText set, then opens a Help dialog with that text. No-op if nothing in the chain has help.

  • post() / post(value) — wake the App’s run-fiber from outside the input / timer paths. See "Externally-driven repaint" below.

  • onPost=(fn) — handler for posted values that aren’t the no-payload sentinel. See below.

  • runChild(fn) — run fn in an owned child while pumping the async App’s events. Return its result or propagate its error, including errors after an Operation await. Early exit cancels the child through its cleanup scopes. See "Async work in handlers" below.

  • onLayout=(fn) — register a callback receiving (width, height) on the first paint and whenever the effective App area changes size. The root Container is resized before the callback runs, allowing the callback to assign stable responsive bounds to its children.

  • onUnhandledMouse=(fn) — register a callback receiving (event, hit) after a non-modal mouse event is declined by the hit widget. hit is the declined Widget, or null when the event is outside the root. Returning true consumes the event; returning false leaves normal App fallback handling, including right-click Escape and drag selection, in place. The callback is not invoked while a modal owns input.

  • theme= — install a custom Theme (see Theme).

Async work in handlers

runChild(fn) spawns a child fiber and pumps the App’s event loop until that child finishes. Use it when a handler should keep input, ticks, and repaints responsive while awaiting an operation. Direct operation await is also safe: its wait defers unrelated wakes, but the handler does not dispatch those UI events until the operation completes.

Call runChild from the active asynchronous App event fiber (including its scoped continuations). Calling from an inactive App, runSync, or an unrelated fiber is an error before the callback starts. Immediate and deferred callback failures propagate as the same error object. Child completion wakes the App even when it has no ticks or incoming input. If the App stops before the child finishes, runChild raises "App stopped before child completed" and detaches the child’s native waits. Registered host cleanup runs without resuming the parked user callback. Operation ownership releases abandoned waits. VM shutdown runs retained cleanup without resuming the parked user callback.

fetchDescAndShow_(path) {
  popStatus("Fetching ...")
  var d = runChild(Fn.new {
    return SFTP.descs(path).await()
  })
  popStatus(null)
  if (d is SFTPError) Alert.show(this, "Failed: " + d.toString)
  else                Alert.showPreformatted(this, d)
}

The child fiber yields on SFTP.descs; the run-fiber drops into its own drainOnce_ loop, dispatching keys, mouse, ticks, and repaints normally while the child is parked. When the SFTP result wakes the child, its body completes and runChild returns the value. Modal calls (Alert, Confirm) belong on the run-fiber side after runChild returns — modals pump drainOnce_ from whichever fiber called them, and only the run-fiber receives wakes from the App’s claim handler.

Externally-driven repaint

The async run() parks the run-fiber on Fiber.yield() between events. A network-driven app (chat client, ticker, log viewer fed by remote bytes) needs a way for Hook.onInput to nudge the UI without faking a key press. That’s what post is for:

import "syncterm" for Hook
import "ui_app"   for App

var app   = App.new()
// ... build widget tree ...

Hook.onInput { |b|
  buffer.add(b)              // mutate state
  someWidget.markDirty()      // mark UI as needing repaint
  app.post()                  // wake the App so drainOnce_ runs again
  return false
}

app.run()

app.post() calls Wake.post(runFiber, WakeOnly.instance) — a no-payload sentinel. The next main-loop drain delivers it, drawAll runs at the top of drainOnce_, and the dirty widget repaints. The hook returns synchronously — post only enqueues, satisfying the hooks-must-run-synchronously rule.

app.post(value) carries an arbitrary Wren value. When a non- sentinel value arrives, onPost (if set) is called with it after the redraw. Pass anything you can recognise:

app.onPost = Fn.new {|v|
  if (v is String && v == "irc.PRIVMSG") chatPane.scrollToBottom()
}

Hook.onInput { |b|
  // ...parse, accumulate...
  if (gotPrivmsg) app.post("irc.PRIVMSG")
  return false
}

post is a no-op when the App isn’t running (no run-fiber). It’s not supported under runSync — the synchronous variant blocks on Input.next() at the C level, not on Fiber.yield, so a wake through the result queue won’t reach it. Use run() for any app that needs external wake-ups.

App is not itself a Widget but exposes effectiveTheme and markDirty() so widget tree-walks can terminate at it. Setting a widget’s parent to an App is supported and is what pushModal does internally.

The built-in Retro directory sets app.menuPanels = true so MenuUi list choices use its full-page panel presentation. The default is false, keeping Classic and custom applications' compact menus. Attached form dropdowns retain their field-relative layout in either presentation.

Widget

Base class for everything paintable. Holds:

  • bounds — a Rect in 1-based screen coords.

  • parent — pointer to the containing Container or App.

  • theme= — a per-widget Theme override; otherwise inherited via effectiveTheme walking the parent chain. Changing an override or reparenting an inheriting widget invalidates affected cached surfaces; an explicit descendant override ends that inherited-theme branch.

  • focused, visible, focusable, activitySensitive, dirty — boolean state flags. Setting activitySensitive to false makes ambient screen chrome use its base theme roles regardless of modal activity; it does not affect focus or input dispatch.

  • atExit — false by default. When true, this widget remains interactive after a sticky process-close request. Modals pushed while it is active inherit the property. Ordinary widgets are unwound through Escape and cannot consume Key.quit themselves.

  • helpText= — string surfaced by App.showHelp (F1).

  • keyHints= — list of [keyLabel, actionLabel] pairs for ambient footer/status UI. App.keyHints resolves it from the focused tree using the same nearest-widget rule as helpText.

  • closesOnOutsideClick(event) — returns whether the App should send Escape to this widget when event occurs outside its modal bounds. The base implementation returns false.

  • shadow= — when true, the parent paints a drop shadow on the cells immediately right and below the widget’s bounds.

  • surface — the widget’s private Surface backbuffer, allocated lazily and resized when bounds changes.

  • preferredWidth, preferredHeight — auto-layout sizing hints. Default null (no preference, fill whatever bounds the parent gives). Widgets with a natural minimum size (ListView with N items, a Form with measured rows, …) override these so containers that know how to lay out children (Pane.fitContent) can size themselves around the content.

Layer-aware painting: every widget tracks the App’s active layer state (whether it or an ancestor is the modal top of stack) and repaints itself when the cached state no longer matches. No tree-wide dirty pass is needed when modals push or pop — each widget notices on its next draw() and repaints with the inactive theme variant. Subclasses override onPaint_() to draw into surface; the base Widget.draw() calls onPaint_(), clears the dirty flag, and returns the surface.

Hardware cursor: cursorPos returns [x, y] in 1-based screen coords (or null); cursorVisible returns whether the cursor should be shown while focused; cursorShape optionally returns "normal" or "solid"; and cursorAttr optionally returns the legacy text attribute whose foreground colors the cursor. App reads all four off the focused leaf each frame and applies them. A visible null shape defaults to "normal"; a null attribute leaves the current conio cursor color unchanged. Containers forward the focused child’s values.

tryHotkey(ev) is a parent-driven hotkey hook. Container.handle scans its children with this when a printable key fell through the focused child, so a typed letter can activate a button advertising that letter even when focus is elsewhere.

Container

Widget subclass that manages a child list, a focused-child index, and event dispatch. add(child) / remove(child) mutate the tree; the first focusable child added becomes focused automatically.

Focus traversal:

  • Tab / Right — focusNext(), ordered ring with wrap.

  • BackTab / Left — focusPrev().

  • Up / Down — spatial nearest-focusable scan. Picks the focusable child whose centre is above / below the current focus’s centre and minimises Manhattan distance. Ties (children on the same row) go to the lower-indexed sibling — i.e. tab order.

Spatial Up/Down does not wrap; it falls back to a hotkey scan if nothing matches. Widgets that need arrows for their own semantics (TextInput consumes Left/Right, ListView consumes Up/Down) catch the keys before they bubble.

Mouse: Container.hitTest(px, py) walks children top-to-bottom (last-added wins) and returns the deepest visible widget covering the point, or the Container itself when nothing under it does.

focusedIndex is readable as a property and writable as a setter for explicit focus management — e.g. the App-level releaseFocus() / restoreFocus() pair clears and restores it around blocking host UIs. The getter returns null when no child is focused, otherwise an integer in 0..count - 1. The setter toggles .focused on the previously- and newly-focused child; pass null to clear focus. Direct day-to-day focus changes still go through focusNext / focusPrev etc., not this setter.

Pane

Container with a frame, optional title, [?] and [X] corner buttons, and an inset interior. The default is a control-bearing pane: the stronger double-line frame, title in its own bar row with a horizontal separator underneath, and both corner buttons enabled.

Configuration knobs:

  • frameKind= — "control" (the default) or "display". A control frame marks a pane that contains choices, buttons, or editable input and uses the stronger double-line family. A display frame marks informational content and uses the single-line family. Assigning any other value aborts the calling fiber.

  • titleAsBar= — when true, the title sits inside the frame in its own row with a horizontal separator underneath. When false, the title is embedded in the top border (-| Title |-). Classic list views use the bar form; Popup subclasses use the embedded form.

  • helpable= / closeable= — show or hide the [?] and [X] corner buttons. Help button calls onHelp if set, else App.showHelp(). Close button calls onClose if set.

  • onHelp=, onClose= — function callbacks for the corner buttons.

pane.innerBounds returns the drawable interior Rect after the frame, title row, and separator are accounted for — children should size themselves against this.

pane.contentBounds is innerBounds inset by one cell on every side so text never touches the frame. Popup-style widgets (Alert / Confirm / Prompt / PopStatus / Help) lay themselves out inside contentBounds; bare Pane use sites that want the full frame interior (e.g. a ListView filling its parent pane) keep using innerBounds.

Pane.focused is a visual flag — set it from the App or a parent container when the pane is the foreground. It does NOT redirect keyboard focus; that still flows through `Container’s normal focused-child routing to a leaf widget inside.

Auto-layout

Pane.fitContent() sizes the pane around its single child’s preferredWidth / preferredHeight, plus whatever the title bar and corner buttons require. It repeats measurement after assigning the child’s bounds, so preferences that depend on the resulting viewport, such as a ListView scrollbar, settle in one call. The width is the largest of:

  • the child’s preferredWidth + 2 (left + right border),

  • the title’s outer-width demand (see below), and

  • the corner buttons' outer-width demand (each visible button contributes 3 cells; total + 2 corners).

The two title modes have different geometry:

  • titleAsBar — title is centered on its own row inside the frame; outer width = title + 4 (frame(2) + 1-cell padding on each side so the title never butts up against the side frame).

  • frameTitle (titleAsBar = false) — title sits in the top frame border between ─ ` and ` ─ brackets; outer width = title + 6 (corners(2) + brackets(2) + spaces(2)).

Multi-child panes are not auto-sized — fitContent only inspects the first child. Lay them out manually via bounds / add.

Pane.fitContent(maximumWidth, maximumHeight) performs the same layout while constraining the complete pane to the supplied maximum dimensions. Pane.fitContentToScreen() applies the standard menu modal limits. It preserves the title row and two-row footer, leaves room for the two-column right shadow and one-row bottom shadow, and centers the result in the remaining work area. For a pane with a requested fixed size rather than a child-defined size, Pane.fitToScreen(width, height) applies those same limits and centering. Pane.modalBounds(width, height) returns that constrained and centered rectangle for manually laid-out shadowed panes.

Pane.centerOnScreen() repositions the pane so its bounds are centered on the current Screen.size, then re-anchors its single child into the new innerBounds. Use fitContentToScreen() for the usual constrained and centered modal layout:

var pane = Pane.new()
pane.title = "ANSI Music Setup"
pane.add(list)
pane.fitContentToScreen()

ListView

Scrollable list of items with a selection cursor and an optional scrollbar. Items can be anything; rendering goes through formatItem(item, width) which subclasses can override for rich per-row formatting. Default is item.toString.

Setup:

var list = ListView.new()
list.bounds   = Rect.new(x, y, w, h)
list.items    = ["alpha", "beta", "gamma"]
list.onChange = Fn.new {|i, item| /* selection moved */ }
list.onSelect = Fn.new {|i, item| /* ... */ }

Navigation: Up, Down, PageUp, PageDown, Home, End move the selection. Enter fires onSelect with (index, item). Mouse: a single click on a row both selects it and fires onSelect; each wheel notch over the list content moves the selection one row using the same wrapping rules as Up and Down. Over the scrollbar, a wheel notch moves one page. The scrollbar’s top and bottom arrow cells invoke PageUp and PageDown; track clicks jump proportionally while keeping the lightbar on the same screen row. The separator column between content and scrollbar is inert. Button-1 drags fall through to screen selection.

wrap= controls single-row Up/Down movement and defaults to true: Up at the first row wraps to the last, and Down at the last wraps to the first. Set it to false to clamp at the ends. PageUp/PageDown, Home/End, and direct selected= assignments do not wrap.

onChange is independent of activation. It fires with (index, item) whenever navigation, assignment, search, or a row click changes the current row. Replacing items also fires it so a detail pane can refresh even when the selected numeric index remains zero. An empty list reports (null, null).

items= preserves the selected index and scrollTop when replacing a populated list, clamping them only when the replacement is shorter. This allows a menu to rebuild changed row labels without moving its viewport. resetItems(list) replaces the collection and explicitly selects its first row at scrollTop=0; use it when navigating to a different collection rather than redrawing the current one.

Repeating MenuUi.choice and MenuUi.commandChoice loops recreate their pane after each activation. Construct one ChoiceViewState before the loop and pass it as the final argument to the callback overload so each pane uses the same ListView; row-label updates then retain both selection and scrollTop. Use a separate state for each logical menu.

selected is null when no row is selected (empty list, or explicitly cleared with list.selected = null); otherwise an integer in 0..count - 1. selectedItem mirrors the same contract — null when nothing is selected, the item otherwise. When a selection is assigned before the list has bounds, first layout centres an offscreen selected row where possible. A selection already in the initial viewport leaves that viewport at the top. Normal navigation scrolls only far enough to keep the moving selection visible.

The selected row is highlighted even when the list does not have focus. Set highlightWhenUnfocused=false in a multi-list control when only the list receiving keyboard input should display its selection lightbar. This does not apply the inactive palette to the other list.

Two complementary search modes, both using Unicode canonical caseless matching and wrapping at the end of the list:

  • Type-to-search — printable text without Control, Alt or GUI grows a rolling buffer and jumps to the first item whose search text starts with it. If the new buffer doesn’t match anywhere, falls back to just the new character (fresh prefix from current+1). Buffer resets on any navigation or activation key, so a paused-then-resumed search starts clean.

  • Ctrl-F / Ctrl-G — Ctrl-F opens an inline Find dialog (see the Popup family) for a substring query, jumps to the first match. Ctrl-G repeats the last query.

Find and repeat-find use the logical key and modifiers, including native C0 Control-letter events from X11, ANSI and curses. Other modified shortcuts, such as Ctrl-S (Sort Profiles) and Ctrl-D (Quick Connect), pass through type-to-search to the menu dispatcher. The Wren console uses Ctrl+` on graphical backends and Ctrl-Q in ANSI/curses modes, where physical key events are unavailable.

The hook searchTextFor_(item) returns the string to match against; defaults to formatItem(item, 1024) (the normal display string). Override in subclasses when the displayed row decorates the underlying text — the SFTP browser’s BrowserListView, for example, returns item.name so users type bare filenames rather than the chip-prefixed [==] foo.dat line.

searchKeys= optionally accepts a List parallel to items, with each value produced by Text.caselessKey(searchTextFor_(item)). A valid list prefilters prefix and substring searches without changing their grapheme-boundary-aware result. A non-List or count mismatch disables the optimization. Replacing items clears the keys, so callers set searchKeys after items.

Tag mode

selectionMode= accepts "single" (default) or "tag". In tag mode each row tracks an independent tag flag, toggled by Space on the current row; tagged returns the indices that are flagged on. A 1-cell marker column appears at the leftmost content position using the theme’s tag.on / tag.off glyphs (» / blank by default; > / blank in ASCII-only mode). Switching modes resets the flags; so does setting items=.

Scrollbar layout knobs:

  • scrollbarSide= — "right" (default) or "left".

  • scrollbarSeparator= — when true, paints a | divider between the scrollbar column and the content area.

  • showScroll= — set to false to disable the scrollbar entirely.

The scrollbar is only painted when items.count > bounds.h.

ListView always reserves a 1-cell padding between the frame and the items on the side that doesn’t have a scrollbar (both sides when no scrollbar is shown at all), so item text never butts up against the frame the parent Pane draws. innerWidth is bounds.w - leftInset - rightInset accordingly.

Auto-layout: preferredWidth returns the longest item’s display length plus the active insets (left + right padding, or scrollbar + padding when overflow is expected); preferredHeight returns items.count, clamped to at least one row. The parent layout owns screen and container constraints. Combined with Pane.fitContentToScreen, a list-in-pane modal sizes itself to its contents:

import "ui_pane" for Pane
import "ui_list" for ListView

var list = ListView.new()
list.items = Host.musicNames

var pane = Pane.new()
pane.title = "ANSI Music Setup"
pane.add(list)
pane.fitContentToScreen() // sized to list, constrained, and centered

Emoji picker

import "syncterm" for Emoji, EmojiEntry provides an offline catalog of canonical emoji supported by all three bundled emoji banks. Emoji.entries returns base representatives; Emoji.search(query) returns exact variants matching a localized name or CLDR keyword substring, using canonical caseless Unicode matching at grapheme boundaries (an empty query returns the base list). English names and keywords are also searchable. Each EmojiEntry exposes text, localized name, keywords (a List of localized and English search keywords, with duplicates removed), and variants. Language preferences are discovered once on first metadata lookup for a host, shared by its menu/picker VMs. Bundled CLDR 49 annotations and derived annotations supply names for joined, gender, skin-tone, and flag sequences. Locale aliases, likely scripts, and CLDR parent locales resolve regional/script preferences; missing fields fall through later preferences, then English. The lookup never changes the process locale or connection encoding and does not require network access. text retains the fully-qualified sequence including joiners and selectors. Entry IDs ending in _ are internal catalog indexes, not persistent values. The picker shows the highlighted name above a parenthesized keyword list, truncated to one line to fit the pane. It uses the screen dimensions with a one-cell margin on each side, reflowing the emoji grid and preserving the selected entry when the screen is resized.

Emoji.recent returns up to 32 exact entries, newest first. Emoji.recordUse(entry) promotes an entry in session recents, then persists the merged recent list. It returns null or a FileError, replacing the former error String in v2. code preserves the exact native IOErr reason; errno is zero because the C operation does not supply a captured errno. The error diagnostic explains that session recents were updated but saving failed. Native partial-write behavior is unchanged; an error does not imply that the settings file is unchanged. No rollback or automatic retry is performed. Successful insertion or transmission is not undone or repeated when recording recents fails; bundled callers log the returned error. Safe mode changes only session memory, performs no file writes, and returns null. This existing fixed-purpose operation is available in menu, picker and connected VMs and grants no arbitrary filesystem access. Invalid catalog entry arguments retain their ordinary Fiber abort behavior. Emoji.canSend reports whether this VM has a UTF-8 terminal connection; it does not restrict local text-field insertion in a menu VM.

App.openEmojiPicker() opens ui_emoji_picker for its focused TextInput. The default bindings are Alt+P and, when Host.localControlKeys is true, Ctrl+P. It returns false without a running App and focused text field. Modal completion preserves the insertion target’s cursor and selection. A changed or detached target is not written. A full field leaves the picker open with an explanation rather than inserting part of a sequence. The mouse wheel scrolls the emoji viewport independently of the selection, respecting its native magnitude and clamping at either end. Keyboard navigation reveals the selected entry again; mouse hit testing uses the scrolled rows.

The connected emoji_pick module uses EmojiFlow.run() for Alt+P and the Online Menu. It saves/restores the screen and mouse settings, suspends terminal output during the picker, and sends a successful selection with Conn.sendText. Ctrl+P is not a connected hook. Local Apps reached through Alt+E use their normal field bindings regardless of the parked connection’s encoding.

TextInput

Single-line text edit field. Stores the value as a list of codepoint strings, so editing indexes codepoints without splitting UTF-8. Cursor placement, scrolling, and painting use Screen.textWidth, which normalizes to NFC and resolves each extended grapheme cluster once. Full grapheme-cluster editing is not currently provided.

insertText(text) inserts a complete String at the cursor (or replaces the whole-field selection). It respects insert/overwrite mode and the codepoint maxLen, returning false without changing the field if the entire payload does not fit or contains C0/DEL controls. Success returns true and emits one onChange callback when the value changes. The picker uses this preflight to preserve joined emoji.

var t = TextInput.new()
t.bounds   = Rect.new(x, y, w, 1)
t.value    = "hello"
t.maxLen   = 64                  // optional cap
t.mask     = "*"                 // optional display-only mask
t.onSubmit = Fn.new {|s| /* Enter */ }
t.onChange = Fn.new {|s| /* per-keystroke */ }
t.selectAll()                     // optional replace-all entry state

Keys use SyncTERM’s standard line-editor behavior. Left, Right, Home, End, Backspace, and Delete / DelChar move and delete; Ctrl-B and Ctrl-E alias Home and End, and Ctrl-Y truncates at the cursor. Insert toggles insert/overwrite mode. Ctrl-C / Ctrl-Insert copy the whole field, Ctrl-X / Shift-Delete cut it, and Ctrl-V / Shift-Insert paste at the cursor. Ctrl-Z opens the focused field’s contextual help when one is available. Enter fires onSubmit; printable codepoints edit at the cursor. Tab, BackTab, Up, and Down are NOT consumed so containers can use them for focus traversal. A left click positions the cursor; middle- and right-click paste there. An unconsumed right-click elsewhere is Escape. Drag events fall through to the App’s screen-selection handler.

selectAll() puts a non-empty value into a transient whole-field selection state, reported by the read-only allSelected getter. The next printable, keyboard paste, Backspace, Delete, or Ctrl-Y operation replaces the complete value. Cursor movement and mouse positioning preserve the value and dismiss the selection before ordinary editing continues; other non-editing key events also dismiss it without changing the value. Assigning value clears the state, so callers opt into it explicitly after assignment when needed.

SelectOnFocusInput is the existing-value editing variant used by SyncTERM prompts: prompts and inline editors. It calls selectAll() whenever it gains focus, clears the selection on focus loss, highlights only the selected text, and uses the surrounding default style after cursor movement begins ordinary editing. Use TextInput when focus should leave an assigned value ready for appending; use SelectOnFocusInput when typing should replace that value.

insertMode reports whether printable input inserts (true, the initial mode) or overwrites existing characters (false). The mode is shared by all TextInput instances, so toggling it in one field applies to the next field. cursorShape is "normal" in insert mode and "solid" in overwrite mode, matching SyncTERM’s insert/overwrite cursor convention. cursorAttr supplies the focused input style’s legacy attribute so bitmap backends render the cursor in the field foreground instead of an unrelated global color. Pasted control characters are discarded, matching typed-input filtering, and maxLen applies to pasted text.

mask= accepts null or a non-empty String and uses its first codepoint when painting every stored character. It does not change value, cursor movement, length, or callback arguments, making it suitable for password and system-password fields. Changing the mask recalculates the horizontal viewport because the replacement glyph may have a different display width.

Assigning or resizing bounds recalculates the horizontal viewport. An initial value wider than the field displays its end followed by a cell for the insertion cursor, regardless of whether value or bounds was assigned first. scrollOff reports the first displayed codepoint index.

cursorVisible returns true and cursorPos reports the cell that corresponds to the current insertion point in screen coords — backends that show the hardware cursor track the input as the user types.

Button

Single-row "[ label ]" widget. Activates on Enter, Space, or mouse click within bounds. onPress= sets the activation callback. intrinsicWidth returns label.count + 4 for sizing parents.

var b = Button.new("OK")
b.bounds  = Rect.new(x, y, b.intrinsicWidth, 1)
b.onPress = Fn.new { app.popModal() }

hotkeyIdx= selects which label letter to highlight (default 0, the first letter). tryHotkey matches that letter case- insensitively against typed input, so a button labeled "Yes" with hotkeyIdx = 0 activates on Y from anywhere in the same container — even when focus is on a sibling.

Checkbox

Single-row "[X] Label" toggle. value is a Bool, label is a String. Space or Enter flips the value when focused; mouse click anywhere on the widget toggles too.

var c = Checkbox.new("Show shadows")
c.bounds   = Rect.new(x, y, c.intrinsicWidth, 1)
c.value    = true
c.onChange = Fn.new {|v| /* ... */ }

onChange fires only when the value actually changes — assigning the current value is a no-op. Theme roles: checkbox, checkbox.focused. Glyphs reused: check.on (√ U+221A), check.off (space).

RadioGroup

Multi-row mutually-exclusive selector. Owns its own item list and selected index — the whole group is a single focusable widget.

var g = RadioGroup.new()
g.bounds   = Rect.new(x, y, w, h)
g.items    = ["None", "SSL", "SSH"]
g.selected = 0
g.onChange = Fn.new {|i, item| /* ... */ }

Two pointers: cursor (visually highlighted row) and selected (the committed value). Up/Down move the cursor; Home / End jump to ends; Space or Enter commits the cursor as the selection. Mouse click selects directly. onChange fires only when the selection actually changes. Both pointers are null when the group is empty (or explicitly cleared by assigning null); otherwise integers in 0..count - 1. The cursor highlight only appears while the widget itself has focus — leaving the group shows just the filled • glyph on the selected row, so a multi-field Form doesn’t confuse the user with a stale lightbar.

wrap= controls the edge behavior of Up/Down. Default true: Up at the top wraps to the bottom and vice versa; every press is consumed. When false, Up at the top and Down at the bottom return false instead, letting the parent Container move focus to the previous / next sibling. Form.addField flips this to false on RadioGroup children so vertical traversal escapes the group at its edges.

Theme roles: radio.item, radio.item.focused. Glyphs reused: radio.on (• U+2022), radio.off (○ U+25CB).

SpinBox

Single-row numeric input with up/down step buttons. Layout: [ 42 ▲▼].

var s = SpinBox.new()
s.bounds   = Rect.new(x, y, w, 1)
s.min      = 0
s.max      = 100
s.step     = 1
s.value    = 50
s.onChange = Fn.new {|v| /* ... */ }

Keys: Up / + adds step; Down / - subtracts; PageUp / PageDown move ten steps; Home / End jump to min / max. Mouse wheel scrolls one step; clicks on the up/down arrow cells step ±1. Pressing an arrow steps immediately; holding it waits 400 ms and then repeats at 8 Hz, accelerating to 16 Hz after two seconds and 32 Hz after five seconds. Acceleration changes only the repeat rate, so every update is still one configured step. Releasing or beginning a drag stops repetition, and a delayed UI wake never produces a burst of catch-up updates. value= clamps to [min, max]. Theme roles: spinbox, spinbox.focused. Glyphs reused: scrollbar.up, scrollbar.down.

DatePicker

Embeddable month calendar with a named month/year header, Sunday-through- Saturday columns, and six date rows. Neighboring-month dates fill unused grid cells and can be selected directly. The control does not provide dialog buttons; its caller owns acceptance and cancellation.

var picker = DatePicker.new(2026, 7, 23)
picker.bounds = Rect.new(x, y, picker.preferredWidth,
    picker.preferredHeight)
picker.onChange = Fn.new {|year, month, day| /* update preview */ }
picker.onAccept = Fn.new { /* commit picker.value */ }

year, month, and day expose the selected components; date returns them as a three-element List, and value returns YYYY-MM-DD. setDate(year, month, day) clamps to years 1 through 9999 and to the selected month’s valid day range. moveDays(offset) and moveMonths(offset) provide programmatic navigation. onChange fires only when the selected date changes; onAccept fires on Enter, Space, or a date double-click.

Left/Right moves one day, Up/Down moves one week, PageUp/PageDown changes month, and Home/End selects the first/last day of the month. Header-arrow clicks and the mouse wheel change month. A single click selects a visible date.

CalendarDate supplies Gregorian helpers used by the widget: monthNames, daysInMonth(year, month), iso(year, month, day), fromTimestamp(seconds), isoFromTimestamp(seconds), daysFromCivil(year, month, day), civilFromDays(days), and weekday(year, month, day) (Sunday is 0). Timestamp conversion is UTC.

Preferred size is 28x8 cells. Theme roles: button, list.item, list.item.focused, and list.item.disabled.

ColorPicker

Embeddable 24-bit colour editor with a compact live sample, editable Red/Green/Blue ramps, visual Hue/Saturation/Value ramps, and six-digit hexadecimal input. The control does not provide dialog buttons; its caller owns acceptance, cancellation, and any application-specific preview.

var picker = ColorPicker.new(0x336699)
picker.bounds = Rect.new(x, y, 44, picker.preferredHeight)
picker.onChange = Fn.new {|rgb| /* update a live preview */ }

value is the current 0xRRGGBB integer. valid is false while the hexadecimal field is incomplete, and commitEdits() returns false until the field contains six valid digits. The RGB ramps accept decimal typing from 0 through 255. HSV ramps remain fully interactive but omit the rounded numeric labels and do not accept decimal typing.

RGB ramps show their numeric value and accept decimal input. HSV ramps do not show rounded numeric values. A digit starts replacement after focus, after a complete or out-of-range entry, or after Delete. Left/Right and the mouse wheel move one unit. PageUp/PageDown move RGB by 16, hue by 15 degrees, and saturation/value by 10 percent. Up/Down moves between fields, and a containing dialog may complete the navigation ring at the picker boundaries. A completed button-1 click jumps to the clicked ramp position. Button presses and drag events remain unconsumed so App can hand drag selection to conio’s normal text-copy path.

sampleColors(foreground, background) replaces the automatic contrasting sample pair. The dialing-directory palette editor uses this to make either row of its sixteen-position contrast grid clickable: selecting a cell shows that foreground/background combination in the larger sample.

Ramp rows use default while idle and list.item.focused for their edge-to-edge focus lightbar. Only the three-character RGB numeric field and the seven-cell hexadecimal field use input / input.focused. Hex input is limited to six digits; the final cell displays the insertion cursor after a complete value without scrolling away its first digit. Complete valid edits are normalized to uppercase without moving the active caret or discarding its selection; assigning ColorPicker.value externally still replaces the field and leaves its cursor at the end.

RGB is the canonical value. HSV conversion retains hue for greys and retains hue/saturation for black, so moving away from those edge cases does not unexpectedly reset the user’s HSV selection. Ramp and sample cells carry both 24-bit RGB and a Color.toLegacyAttr() fallback.

The dialing-directory palette editor composes this generic control with a separate palette-only preview. That preview shows the candidate colour as both foreground and background against all sixteen effective palette positions; this behavior is not part of ColorPicker. In that dialog, Home selects the first ramp and End selects the button row when a ramp has focus. The same keys retain normal text-cursor behavior in the hex field.

MenuBar

Horizontal strip of activatable items, typically at the top of the screen. Each item is a [label, Fn] pair; activation calls the Fn. No nested submenus in v1 — pop a Popup from the callback if you want one.

var bar = MenuBar.new()
bar.bounds = Rect.new(1, 1, sz[0], 1)
bar.items  = [
  ["File", Fn.new { Alert.show(app, "...") }],
  ["Edit", Fn.new { /* ... */ }],
  ["Help", Fn.new { app.showHelp() }],
]

Keys: Left / Right move focus between items with wrap; Home / End jump to ends; Enter / Space activate the focused item; a typed Unicode scalar (canonical caseless) matched against item labels' first characters activates that item. focusedItem is null when the bar is empty (or explicitly cleared); otherwise an integer in 0..count - 1. tryHotkey(ev) is exposed on the widget so a Container parent can route a letter pressed elsewhere into the bar’s matcher. The focusedItem cursor is painted with the focused role only while the MenuBar widget itself has focus, so multiple bars may retain their navigation positions without appearing simultaneously active. Set onFocus= when a containing editor needs a mouse click to move its own focus to the bar before activation. A completed mouse click activates the clicked item; the initial press and any drag do not. Clicks on inter-item gaps are dropped. Theme roles: menubar, menubar.item, menubar.item.focused.

StatusBar

Single-row strip used at the bottom (or top) of the screen for status text and key hints. Not focusable.

var s = StatusBar.new()
s.bounds = Rect.new(1, sz[1], sz[0], 1)
s.text   = "F1 Help  Esc Quit"

// or — multi-segment:
s.segments = [
  ["F1 Help",   "left"],
  ["Connected", "center"],
  ["09:42",     "right"],
]

text= sets a single left-aligned string. segments= takes a list of [text, align] pairs where align is "left", "center", or "right". Left segments stack from the left edge with a 2-cell gap; right segments flush to the right edge inward; one center segment is centred in the remaining space. Setting either form overrides the other. Theme role: statusbar (black on cyan).

Form

Container subclass that lays out (label, widget) pairs in a vertical stack with right-aligned labels in a column on the left. Optional OK / Cancel buttons appear on the row below the last field when onSubmit / onCancel are wired.

var f = Form.new()
f.bounds = pane.innerBounds

f.addField("Name:", nameInput)
f.addField("Port:", portSpin)
f.addFieldH("Encryption:", encRadio, 3)    // 3 rows tall
f.addField("",  autoCheckbox)              // no label

f.onSubmit = Fn.new { /* read field values */ }
f.onCancel = Fn.new { app.quit() }
pane.add(f)
  • addField(label, widget) — queues a one-row field.

  • addFieldH(label, widget, h) — queues a multi-row field (e.g. RadioGroup).

  • clearFields() — drops every queued field and removes the widgets as children.

  • rowGap= — blank rows between fields. Default 0.

  • rowH= — default per-field height. Default 1.

The label column width auto-sizes to the longest label; widgets start one column past the longest label plus a 2-cell gap. Form keeps its managed child order as fields in addField declaration order followed by the implicit OK and Cancel buttons, regardless of when their callbacks are assigned. Container’s normal insertion-order Tab / BackTab traversal then uses that order. Esc fires onCancel if wired.

onSubmit= / onCancel= are idempotent setters — assigning the same callback twice doesn’t double-add the OK / Cancel button, and assigning null removes the button.

Popup family

Modal dialogs built on Pane (control frame, embedded title, drop shadow) and pushed onto the App’s modal stack. Each show is synchronous: the App’s modal() pumps drain until the popup pops itself, then control returns with the result. Help is the informational exception and selects the display frame; transient PopStatus uses the display frame as well.

import "ui" for Alert, Confirm, Prompt, LinePrompt

Alert.show(app, "Disk full")
Alert.show(app, "Warning", "Disk full")
Alert.show(app, "Warning", "Disk full", "# Disk Full\n\nFree space first.")

if (Confirm.show(app, "Delete file?", "# Delete\n\nThis cannot be undone.")) {
  // ...
}

var name = Prompt.show(app, "Your name?", "anonymous")
if (name != null) {
  // user submitted
}

var path = LinePrompt.show(app, "Path", "/tmp")

Alert — single OK button. Enter, Space, O, Esc, or a mouse click on OK dismisses it; unrelated keys do not. show returns null.

Confirm — Yes / No buttons. Y / N letter shortcuts dismiss directly; Enter activates the focused button; Tab cycles focus. show returns true on Yes, false on No or Esc.

The four-argument titled Alert.show(app, title, message, helpText) and three-argument Confirm.show(app, message, helpText) forms attach Markdown context help to the popup. F1 and Ctrl-Z display that text while the popup owns focus.

Prompt — SelectOnFocusInput plus OK / Cancel buttons. A non-empty initial value starts selected: typing, keyboard paste, Backspace, or Delete replaces it, while cursor movement or mouse positioning preserves it and begins ordinary editing. Enter in the input or on OK submits the value; Esc or Cancel returns null. The read-only input getter exposes that input so trusted UI code can set maxLen or a display-only mask before presenting the popup.

Prompt.new(message, initial, true) creates a required prompt. Escape keeps the current edit in place and Enter accepts the field, including an empty value.

sizeForInput(inputWidth) and sizeForInput(inputWidth, minimumWidth) size the field for the requested capacity and cap the complete popup to the standard menu modal work area. The MenuUi.prompt wrappers use the field’s maxLen for this width. Short fields retain the normal minimum while URI, path, password, and other long fields use the available screen width.

LinePrompt — compact UIFC-style single-row entry. Its label appears to the left of the input on the only interior row; there is no OK / Cancel button row. Enter submits and Esc returns null. The read-only input getter and sizeForInput methods have the same purpose as Prompt’s. A distinct optional title may be placed in the top frame, but menu prompts omit it when it would merely repeat the field label. MenuUi.prompt uses this form for ordinary menu editing and application filename entry; host prompts retain Prompt because their explanatory message is separate from the dialog title. LinePrompt.runStandalone(app, label, initial) is the standalone equivalent.

Find — compact single-row variant of Prompt. Title sits in the top frame border, the input fills the entire innerBounds row (no padding, no buttons, no [X]). Total height is 3 cells. Its previous query starts selected under the same replacement rules as Prompt. Used by `ListView’s Ctrl-F.

import "ui" for Find

var q = Find.show(app, "Find", lastQuery)
if (q != null && q.count > 0) {
  // ...
}

Layout

All popups use the standard frame interior padding via Pane.contentBounds — a 1-cell pad on every side so text never touches the frame. Buttons (Alert OK, Confirm Yes/No, Prompt OK/Cancel) anchor hard against the bottom frame; the empty row between the message and the button row falls out of the height math as a natural visual separator.

Popup.centeredBounds_(message, extraRows, minW) sizes the dialog around the wrapped message: width is longest-line + 4 (frame
padding), height is 4 + msgRows + extraRows (2 frame + 2 padding
content). Subclasses pass extraRows for whatever they paint below the message — 1 for Alert/Confirm (button row), 2 for Prompt (input + button rows). Message width is measured in display cells with the resolved default style font; wrapping never splits a UTF-8 codepoint. A single glyph wider than the available row remains intact and is left to the painter’s clipping policy.

PopStatus is the non-modal companion: a centered frame with a message and no buttons, used by App.popStatus(message). It does not push onto the modal stack — purely decorative — and is dismissed with app.popStatus(null). Its sizing, centering, and single-line truncation use the same painted-font display widths, and truncation stops only at a Unicode codepoint boundary.

Standalone popups

Confirm.show(app, …​) (and the other Popup.show family methods) expect app to already be running — they call app.modal(p), which pumps drainOnce_() on the existing run loop’s input claim. When you need a popup from a context with no enclosing app — a Hook.onKey handler being the canonical case — use the standalone variants, which push the popup, wire onDismiss to app.quit(), and run the App so key events are routed:

var app = App.new()
if (Confirm.runStandalone(app, "Disconnect... Are you sure?")) {
  // user clicked Yes
}

Standalone helpers are available as Alert.runStandalone(app, msg), Alert.runStandalone(app, title, msg), Confirm.runStandalone(app, msg), and Prompt.runStandalone(app, msg, initial).

For custom popup drivers, onDismiss=(fn) fires from dismissWith_ after the popup pops itself off the modal stack, with the dismissed value (Bool / String / null depending on the popup subclass). If you call app.run() yourself, wire onDismiss to app.quit(); otherwise app.run() would loop forever on an empty modal stack.

Help viewer

A modal scrollable text viewer for context help. The body is parsed once as a markdown subset (see "Markdown subset" below) and laid out lazily — text wraps to the dialog width and reflows on resize.

Set literal = true on a Help instance to display plain text with wrapping and scrolling, preserving punctuation such as Markdown markers. This mode is used for the embedded license notices. preformatted = true instead keeps source lines unwrapped; combining it with literal also disables inline Markdown parsing.

import "ui" for Help

Help.show(app, "Help — Editor",
          "# Editor\n\n" +
          "- `Up`/`Down`  scroll\n" +
          "- `Enter`     close\n")

Keys: Up, Down, PageUp, PageDown, Home, End scroll; any other key dismisses. Wheel scrolls one line over the text and one page over the scrollbar. Scrollbar clicks jump proportionally; button-1 drags fall through to screen text selection. An ordinary mouse-button click also dismisses, including a click outside the dialog. Same scrollbar knobs as ListView (scrollbarSide=, scrollbarSeparator=). Clicking the frame’s [X] corner button dismisses (inherited from Pane).

App.showHelp (F1 by default) walks from the focused leaf up the parent chain looking for a widget with helpText set, then calls Help.show with the title "Help" and that text. Set helpText on whichever widget is the most-specific scope you want help to fall back to.

App.helpText, App.helpAvailable, and App.keyHints expose that same focused context without opening a dialog. The main-menu footer queries these values only when it paints; command ownership remains with the focused widget or its nearest containing pane. Custom modal widgets should set keyHints for their direct commands. The standard choices, prompts, popups, and Help viewer already do so.

Prompts and other modal widgets can also carry helpText. Because the focused input or list is their child, the same parent walk finds the modal’s field-specific help before any help attached to the underlying screen.

Default placement: Help.centeredBounds_() uses the standard menu modal work area. The frame remains below the title row, its bottom shadow remains above the two-row footer, and it retains the 2-cell horizontal margins. Pass an explicit Rect via the bounds= setter after construction to override.

Padding: 1-cell margin on every side except the scrollbar column, where text is flush. The scrollbar defaults to the right, and its column plus optional separator span the full inner height (between the top and bottom frame chars); only text rows inset by the top/bottom padding.

Markdown subset

Help body strings (and any helpText) are parsed as a small CommonMark + Pandoc subset by ui_markdown.wren. Supported syntax:

  • Block: # / / # headings; - ` or `* ` bullets; blank-line- separated paragraphs; Pandoc-style definition lists (term line followed by one or more `: description lines).

  • Inline: bold, code . Backslash escapes a literal *, ` , or \ outside a code span. Inside a code span, only the closing backtick is syntax: bold markers and backslashes are literal. Closing code resumes the surrounding bold or ordinary role.

  • Hard line break: a line ending in two trailing spaces forces a break at that point inside a paragraph or bullet. Continuation uses the same wrap indent as a soft wrap (so a bullet’s hard- break still hangs under the text). An unmarked source line belongs to a bullet only when the preceding bullet-owned line has this hard break; the rule can chain across multiple lines.

  • Italics are intentionally omitted — terminal italic support varies and dim grey on dark blue is hard to read.

Each block-level token resolves to a style role (help.heading.1, help.bold, help.code, help.bullet, etc.) that cascades through help and finally default, so themes can restyle without touching the parser. Unknown markup falls through as literal text.

Definition lists pad each term to a common column width — capped at half the dialog — and wrap descriptions inside the description column, with continuation lines indented to the description start. Term and description default to help.bold and help.text respectively.

Headings render as a single-row reverse-video bar: blue-on-cyan text with one styled space cell on each end (" Title ").

Layout is reflow-on-width: Markdown.layout(doc, cols) returns a list of MdLine`s, each carrying pre-resolved style runs ready for `Painter.text. The public layout helper uses font zero; Help measures every run with the font resolved for that run’s role so its layout matches painting. Help re-runs layout whenever its bounds, scrollbar-separator width, or effective theme changes (as well as when the scrollbar appears or disappears), and clamps the scroll position accordingly.

Example combining heading + def-list:

# Capture Type

ASCII
:  Plain text, no escape sequences
Raw
:  Preserves ANSI escape sequences
Binary
:  Saves the current screen as IBM-CGA / BinaryText

Theme, Style, Glyphs

A Theme bundles a role → Style map and a Glyphs (name → glyph) lookup. Style is a four-field tuple (font, legacyAttr, fgRgb, bgRgb); any field may be null to inherit from a parent role. Painting picks one of the two color paths based on what the backend supports — RGB on capable terminals, legacy attr otherwise.

Role cascade: Theme.style(role) walks dotted role suffixes, merging partial Styles at each level until every field is populated. "list.item.focused" falls back to "list.item" falls back to "default". "default" is the cascade terminator and must be a complete Style.

Inactive cascade: when a role ends in .inactive, the Theme walks a parallel chain — X.inactive, then parent(X).inactive, …, finally default.inactive. Falls through to default if the theme has no inactive variants at all. Widget.style(role) auto-suffixes .inactive whenever inActiveLayer is false, so a single layer-state flag cascades through frame, title, list rows, input field, button labels, and scrollbar without per-widget bookkeeping.

A widget lands in the inactive layer for either of two reasons:

  • It isn’t part of the App’s modal-top subtree (a modal is on top, and the widget is in the layer behind it).

  • An ancestor that gates focus visibility has focused == false. Widget.gatesActiveLayer defaults to false; Pane overrides it to true, so an unfocused Pane in a multi-pane layout dims every cell it owns AND every descendant’s surface — frame, title, bg fill, list rows all agree on active-vs-inactive without each subclass having to know.

activitySensitive=false opts a widget out of this style selection. It continues to report its computed inActiveLayer value, but style(role) always resolves the base role. This is intended for ambient screen backgrounds, title bars, and status/help bars which do not have active and inactive forms. Do not use focusable=false for this purpose: display-only children such as progress bars still need to inherit an inactive containing Pane.

Theme.default is the C-owned compiled fallback decoded into Wren and memoized so someTheme == Theme.default works as identity equality. Theme builders use it to populate roles and glyphs they do not override, and an unattached Widget falls back to it when it has no Theme in its parent chain. It uses a white-on-blue palette, yellow frame/title, lightbar selection, gray-on-blue scrollbar, and bright-white-on-cyan inactive palette.

Theme.current decodes Host.themeData and caches the result against Host.themeGeneration. App.new() initializes from this process-wide selection. The built-in Classic Theme and file themes use the same host representation; their storage and complete role/glyph registry are documented in Themes.adoc. Scripts may still construct a Theme directly or assign app.theme to replace the program theme for one App. Such a Wren object does not modify the C-owned selection or any other VM.

Theme.fromData(data) constructs an independent Theme from the same [styleRows, glyphRows] representation returned by Host.themeData and ThemeDocument.themeData. It is intended for draft previews and other host-provided snapshots; modifying the returned object does not modify its source or the process-wide selection.

Glyphs entries are either a single string or [primary, fallback] pairs — primary is the rich Unicode glyph, fallback is an ASCII-safe substitute. The host resolves each theme glyph at load time in Codepoint, CP437, then ASCII order and supplies the resulting Unicode primary to Wren. Glyphs caches that primary by name. Set theme.glyphs.asciiOnly = true to force the fallback for every entry that has one — useful when the user has selected a font that can’t render line-drawing characters at all.

Glyph families used by the library:

  • frame.display.* — single-line -- borders for informational viewers, plus tee.left/right, title.left/right, and separator.

  • frame.control.* — double-line == borders for panes containing choices, buttons, or editable input. Pane.frameKind selects between the two frame families.

  • scrollbar.track, scrollbar.thumb, scrollbar.up, scrollbar.down, scrollbar.separator — scrollbar pieces.

  • focus.left, focus.right — selection-arrow shapes. Existing atlas arrows use list.item.focused.indicator and its .inactive variant for colours; these inherit the selected-row styles unless overridden. Ordinary ListView rows do not draw these arrows.

Painter

Painter is the low-level drawing toolbox. Every primitive takes a Surface as its first argument and mutates the cells in place; no calls reach Screen.putRect from here. Coordinates inside a Surface are 0-based (0..width-1, 0..height-1); widgets that work in absolute screen coords convert at composition time.

The most useful entry points:

fill(s, rect, ch, style) Bulk-fill a Surface rect with a single character + Style.

text(s, x, y, str, style)
text(s, x, y, str, style, maxW)

Draw str on a single row. 6-arg form caps at maxW cells. A glyph that cannot fit completely is not drawn and leaves its destination cell unchanged.

frame(s, rect, glyphs, style)
frame(s, rect, glyphs, style, prefix)

Box around rect using prefix.* glyphs. The default is "frame.display"; pass "frame.control" for a control-bearing pane.

frameTitle(s, rect, glyphs, frameStyle, title, titleStyle, prefix)

Frame with a centered `+

Title

+` in the top border.

hline(s, x, y, len, ch, style)
vline(s, x, y, len, ch, style)

Single-row / single-column lines. hline likewise leaves the destination unchanged when its next glyph cannot fit completely.

scrollbar(s, x, y, h, scrollTop, total, viewport, glyphs, trackStyle, thumbStyle)

Vertical scrollbar with always-visible up/down arrows on the top/bottom rows when h >= 3. Thumb stays inside the track between the arrows.

scrollbarClick(py, h, total, viewport, current)

Resolve a click at row py (0-based, scrollbar-local) into a new scrollTop. Top/bottom arrow rows step ±1; track clicks jump proportionally.

shadow(s, x0, y0, w, h)
shadow(s, x0, y0, w, h, style)

Paint a drop shadow on the cells around the rect: 2 columns wide on the right, 1 row tall on the bottom. Each shadow cell keeps its existing character and font. The five-argument form uses the compiled shadow style (legacy 0x08, RGB fg 0x202020 on bg 0x000000). The six-argument form applies non-null colour fields from style. Widget composition supplies castingWidget.effectiveTheme.style("shadow"), independently of activity.

applyStyle(cell, style)

Apply a Style to an existing Cell, leaving null fields untouched. Exposed for callers that mutate a cell view directly.

UI Modules

The library is split across one module per topic, plus the convenience aggregator:

ui

Re-exports every public class.

ui_app

App.

ui_widget

Widget, Container, Rect.

ui_pane

Pane.

ui_list

ListView.

ui_input

TextInput, SelectOnFocusInput.

ui_button

Button.

ui_checkbox

Checkbox.

ui_radio

RadioGroup.

ui_spinbox

SpinBox.

ui_date_picker

DatePicker, CalendarDate.

ui_color_picker

ColorPicker.

ui_statusbar

StatusBar.

ui_menubar

MenuBar.

ui_form

Form.

ui_popup

Popup, Alert, Confirm, Prompt, Find, PopStatus.

ui_help

Help.

ui_draw

Painter.

ui_style

Style, Glyphs, Theme.

Demo gallery

scripts/ui_demo.wren is a playground for the library; run it from the Wren console (see Built-in REPL):

import "ui_demo" for UiDemo
UiDemo.run()

Top level is a list of widget demos; pick one with Enter to launch it, Esc returns to the gallery. Each demo runs its own App via runSync (the console blocks the main loop, so doterm can’t dispatch through to a parked fiber); nesting is fine because every App restores mouse subscriptions, cursor shape/position, and text attributes. The caller uses Screen.save/restore or Screen.modalRun to restore screen contents.

Worked Example: Auto-respond to a Prompt

A small script that watches inbound text for known prompts and sends canned responses. Hook.onMatch is the right tool for this — it runs a streaming regex against the inbound byte stream and fires the callback on each match, no manual buffering required:

import "syncterm" for Hook, Conn

Hook.onMatch("Press any key to continue") { |m|
  Conn.sendText("\r")
}

Hook.onMatch("Logon: ") { |m|
  Conn.sendText("myhandle\r")
}

onMatch is passthrough-only, so the matched text always reaches the terminal — the callback just acts on the side (sending bytes back to the BBS, updating script state, etc.). When a prompt is preceded by colour codes, use Hook.onMatchClean instead so the escapes don’t break the literal match.

onMatch substring-matches anywhere in the stream, not anchored to line boundaries, so prompts that wait for input mid-line (like `Logon: `) work the same as prompts followed by a newline. See Hook Events for the regex grammar accepted, including which constructs aren’t supported (no character classes, no anchors, no backslash escapes).

Worked Example: Per-byte Inspection

Hook.onInput is the lower-level primitive — fires once per inbound byte before the byte reaches the terminal. Use it when you need to react to individual bytes rather than text patterns. Below: count BEL (0x07) bytes received over the session.

import "syncterm" for Hook

class Stats {
  static bells { __bells }
  static bells=(n) { __bells = n }
}
Stats.bells = 0

Hook.onInput { |b|
  if (b == 0x07) Stats.bells = Stats.bells + 1
  return false
}

Inspect the count from the Wren console (see Built-in REPL) — Stats.bells returns the running total. Returning false lets the byte through to cterm; returning true would consume it (so the BEL never reaches the terminal and never beeps). Filtered variants — Hook.onInput(0x07, fn) — push the byte equality check to the C side, avoiding a Wren entry on every non-target byte.