Skip to content

TypeScript

For a step-by-step introduction to using this Core in an application, see Embed the TS Core in a TypeScript app. It opens with the Helpers, createGroup, script.handlers and inlineGrants, which take and return plain JS values (ADR 0130); the Helpers example runs that code.

A Result Target, into name, retains the answer of an ask, a tell-block Operation line, a Command Call (including a Host Command), a call statement or a waiting send (ADR 0114). It writes the bare Name with put semantics and keeps it; and wait remains last. Fire-and-forget calls reject targets, and a Message Path Command Call or explicit send needs explicit and wait. A Join records each reached member’s destination and assigns them in start order only after every answer converts and all completion charges are reserved, so duplicate targets retain the last-started answer and failure writes no member targets. Saves retain the member instruction and its owning frame, including early answers and repeated destinations.

The TS Core supports lazy otherwise and map-only the optional k of x reads, including computed keys, Constants and Guards. See the migration guide.

The TS Core constructs and encodes values, parses and checks source, lowers it to the Abstract Machine, and runs Scripts through the embedding API. Its Session Host supports Entries, Session Commands, Transcript recording and replay; the CLI provides the REPL. The Spec and Data Files remain the authority; limitations are described beside each feature below.

Run commands in this guide from the repository root. Workspace-only scripts select their package explicitly with --cwd.

Runtimes: every published entry point supports Bun and Node 24.10 or later, including applications using only the Core, and CI checks both. Browsers support every subpath except /sqlite and /http; the notification router (/notify) is browser-compatible. Deno isn’t supported (ADR 0083).

A Timeout Block, with timeout of d … end timeout, bounds the waits written inside it (ADR 0073). timeout-start pushes a deadline, the Clock reading plus d or the enclosing block’s when that is no later, which stays on the stack below the body as an iterator does, so Unwind depths count it and a catch outside the block drops it. exit repeat and next repeat emit timeout-end for each block they leave. Each Suspension Point reads the topmost deadline on its frame’s stack: past it, the instruction raises timeout with deadline: true at once, and otherwise the block’s deadline replaces the wait’s own timer when it is no later, or for a Join, is a timer of its own set before its members’. The checker reports not in a timeout and empty timeout, and a Host Fail may not use the reserved key deadline.

A tell g block calls each line’s Operation of the Grant g (ADR 0063). The parser reads end as the block’s close and any other first word as an Operation name. Each line is an ask until the checker resolves it against the unit’s Grants: a fire-and-forget Operation’s line without and wait becomes a tell, once, so an importing Script’s recheck tests the Library’s lines as compiled. Lines then lower, check suspension and join as the one-line calls they stand for, at their Operation names. A Grant the unit doesn’t hold is one unknown operation at the block’s receiver. With no Grants, as in Disassembly Cases, every line lowers as an ask. DefineCapability refuses end as an Operation name.

Any repeat head accepts collecting e into v (ADR 0059). The target is a local initialized to [] before the head is evaluated. Each completed pass appends one value after the body; next repeat and exit repeat skip it, and an error keeps the partial list. Bodies may read the target and suspend, but Container writes, pattern bindings and inner collecting clauses cannot write that target. Targets clash with Script Variables, Constants, well-known objects and the loop’s own iteration bindings.

Whose Clauses (ADR 0074) parse as a whole Expression: an Every Head (every item of xs whose …) is decided at the start of one, and an ordinal Chunk Expression takes whose only when it is the whole operand. The Syntax Tree has Whose, EveryHead and WhoseKey nodes; a Whose Key isn’t a name, so it is never resolved or renamed. The checker reports not in a whose at a condition’s non-Built-in call or Lambda, and an unknown name in a condition suggests it's in its message. Lowering walks the plural property with iterate and next, and it in the condition loads the innermost clause’s temp, as chapter 8 lays out.

Maps use persistent balanced trees for key lookup and insertion order. Lists use persistent balanced trees of at most 32 values per chunk. A Map key write, a List point replacement or deletion, and List growth with put … after/before, spreading or collecting copy only the affected tree paths and chunks. Their storage work is O(log n) per changed item, including branches from retained values. Replacing or deleting a List range still rebuilds the result. Retained values, Segment checkpoints and Host reads keep their original contents. Logical contents sizes are cached and updated incrementally, as if nothing were shared; Fuel and logical allocation follow the unchanged Cost Model, including charging the full result size for collecting. Save/Restore uses the same value format and reconstructs independent storage.

Text chunk reads segment the input once and reuse those units for counting and selection. Character reads slice the original Text at Character boundaries; ASCII without CRLF can use UTF-16 offsets directly. All other Character reads use the pinned Unicode segmenter. Results still pass through the NFC Text constructor, and scanned, Fuel, logical allocation and saved Values follow the same rules on both paths. No boundary cache is retained in Values or saves.

Whole Host Object properties can be assigned with set through me, it or the target, including intermediate keys/chunks that locate the Object. These implicit bindings cannot be replaced or used as roots for ordinary Container mutations. set does not modify chunks inside a property’s value. Direct known-owner read-only properties are checked at load; it and Target properties are checked at runtime (ADR 0085).

Recovery Offers: this Core parses, checks, lowers and executes offers and two-phase catch search. Ordinary catches test before cleanup; recovery policy can choose a retained local/Library/same-Run action. offerAvailable, canonical metadata, costs and choice/entry Trace records are implemented. Nested policy searches stay within their selection boundary; escaping policy Errors carry during outward, transfer cleanup preserves or cancels choices as appropriate, and cancellation enumerates dispatch-local and retained scopes once. Dispatch saves retain control stacks, shared owner locals, pending transfers, cleanup progress and attempt numbers. Restore validates every retained code/body/PC, ownership chain, target and cleanup reference before resuming; search and lookup preempt only at the following instruction boundary. Save/restore evidence covers ordinary catches, nested policy, transfer cleanup, action entry and cancellation. Session Scripts can choose Library offers and replay their Transcripts. The shared TS debugger follows active dispatch control and display retained frames with shared owner locals; Go reproduces their execution Traces through its replay backend. See the tooling/session evidence and language rules.

Use the TS and tooling task map for implementation files, Spec links, tests and root-relative check commands.

Named Script Function Values display as <function session:double> even when an extension defines them; imports retain their defining Library and declaration name. The defining code unit remains part of equality and call identity, so a redefinition can produce unequal Function Values with the same display.

Implemented commands: Session observation adds :describe, :inspect, :apropos, :trace/:untrace, :fuel, marked declaration docs and object-crossing Transcript envelopes. This Core implements the public Run accounting reports, RestoreResult.reports, Declaration Documentation (#436), :describe and :apropos (#437), and :trace, :untrace and :fuel (#438). It also implements :inspect and object-crossing envelopes (#439); coordinated release review remains in #370.

  • Value inspection and object Transcripts: :inspect accepts one expression, including a multiline expression, and evaluates it once. Syntax and checking diagnostics use the expression’s own source positions; statements, declarations and trailing input give ! bad arguments. Passive rows show the held value, sizes, sorted map fields, Function metadata/docs or the actual Object Kind’s properties. An object then runs the generated normative reader as a separate ordinary request with the current limits; getters run once in code-point order and print one-level results or parity-safe errors. Generated readers stay out of Session Source/export. New recordings include initial % setup and portable Function exposures; recordings without % still replay with their original empty-object setup.
  • Object adapters: supply objects(context) in SessionEnvironment; use SessionObjects.defineKind and .object for initial and dynamically returned identities, and .action for normalized external worker requests. The adapter records actual callback boundaries, ordered queued actions, errors and synchronous refusals. Supply resolveObject for live Restore. Standalone replay creates dummy native identities and consumes these records through normal Core Shape checks and costs; it does not invoke the original getter or external I/O. Function references retain actual exposed Values, preserve nested map insertion order and become invalid after successful Restore. Corpus replay uses the same envelopes in both Trace modes. The proposed first expectations still await human first-blessing review.

Queued parent changes recheck cycles and disposed children at drain, including children unresolved by Restore. A change that becomes invalid leaves the parent unchanged, writes refused, and returns a {kind: "host error", code, detail?} Pump report; later inputs still drain. The detail is Host-only and outside parity.

  • Declaration Documentation: --| blocks attach to the next top-level declaration as the specification says. A leading block keeps an Entry incomplete(), and the Host refuses a block that documents nothing with ! bad arguments. The source a declaration was entered with keeps its block, through redefinition, export and reload. documentation(name), libraryDocumentation(library, name) and functionDocumentation(value) return the documentation. Each Handler Clause has its own entry. An Import resolves to the declaration that defines it, and a Built-in uses its stdlib.toml description. A Function Value’s documentation comes from the code that defined it, so a stale one keeps its documentation, including across save and restore.
  • Tracing and Fuel: the Session Host reads only the public Run accounting reports for these commands. :trace filters latch a dispatched Run by its message Selector when it starts; a Command Call shares its caller’s Run and is not traced separately, and a Function Value’s Run has no Selector to match. trace start and trace end rows follow a Host call’s ordinary output, and Fuel rows follow them. :fuel <entry> measures the Entry’s root Delivery and every Run and message spawned from it, summing each member Run’s latest cumulative Fuel. It stays pending until the root’s causal work reports no live Runs and no queued messages. incomplete() waits for a multiline :fuel Entry. :save keeps filters, latched Runs and measurements; :restore prints fuel abandoned for each measurement still pending, then continues from the saved ones. The sessions/observation case pins the output on both Cores.
  • :describe and :apropos: both read declaration source and the Built-in catalogue, so they execute nothing. Describing a current Script Variable takes one explicit vars snapshot for its value rows; no other lookup reads the Group. A signature ends at the declaration’s grammar head: a function’s or Handler’s head line, or a Constant’s or Script Variable’s name. A stale Function Value keeps its original name, arity and documentation through save and restore, even after its executable code is discarded. Describing an Object variable renders its actual Kind metadata without calling getters.

@northtalk/ts/session exports SessionHost, chapter 12’s Session Host. It does no I/O of its own: its environment supplies the Clock and takes the Trace, and each call returns the lines the session printed.

  • Entries: a Session recognises a Handler Selector by its first word. parseEntry(source, isHandler) decides an Entry on its first token, and says whether a failed parse ran out of source, so a REPL can read more lines. input() keeps the session source, extends the Session Script with new declarations and with an implicit entry<n> Handler for each statement or expression, and reloads it, carrying Script Variables over, for a redefinition. Diagnostics and errors are shown in the Entry’s own lines. incomplete(source) lets tooling line prompts use the same current Handler recognition, including labelled calls continued inside brackets.
  • Implicit Script Variables are the Container roots an Entry puts into, and the names its binding Captures bind. A pattern’s names stay the Run’s locals, since a pattern may not bind a Script Variable.
  • Lifecycle failures: returned effect failure reports render their Grant, Segment, phase and status, and effect-failed Run outcomes print ! effect failed. Effect-failed Runs never print an expression success value. Outside-Pump cleanup reports render too; fatal cleanup keeps the previous Session Source and user Library definitions. Session mocks have no scope or Segment-bound declarations.
  • Following Runs: the Session Host follows its Runs through a TS-internal hook that gives the Trace’s seg, call, run and unhandled records as typed values (ADR 0045). It never calls inspect() to decide what to print.
  • The foreground: waiting says whether the Foreground Run waits on read, which read() answers, or only for a deadline, at which the caller tick()s; otherwise the Run goes on in the background, and its lines are printed after [<run>] .
  • Session Setup: host.setup declares the Group for both the live Session Host and Trace replay. @northtalk/ts/setup owns the Setup data model and Group builder; the Host supplies live Capabilities and replay supplies recorded answers or Stubs. Grants and mocks produce new immutable declarations before the session starts, and Library imports and Object recordings are carried into replay. host.exportManifest() derives the Session’s Host Manifest without starting it. Store, Calendar and Locale sessions replay through both fixed Trace replay and the incremental replay Host; Store bindings keep aliases on the same named Store.
  • Session Transcripts: parseTranscript, writeTranscript and replayTranscript read, write and replay chapter 12’s lines. Replaying gives each @ reading to the Pump the line before it causes, and makes a Pump at each other @. bun run corpus:run runs each kind = "transcript" case through a fresh Session Host, matching its output lines and its Trace, and then replays its case.trace as a Trace Case, in both replays, with the Host’s immutable Session Setup, including the Session Script, free console, mock and extension declarations, Standard Capability costs, and each Grant’s binding. --bless fills in the output lines and writes case.trace.
  • Mocks: :mock, :grant, :stub, :answer, :fail and :charge work as chapter 12 says, and a read-only suspending mock is metered. A mock Operation declares eight Optional any arguments and no error codes, and costs nothing. Its Stubs come from Stubs in src/session/stubs.ts, which the Trace Case runner uses too, and each :stub writes its stub line into the Trace. A Transcript’s Trace Case setup adds each mock Operation and Grant the session started with.
  • The Clock, limits and Runs: :clock shows the Clock, switches it between real and virtual, and advances a virtual one and pumps; a virtual Clock is read by every Pump, and a foreground deadline wait returns the prompt at once. :limits tightens the override later Entries are requested with. :cancel cancels the latest Entry’s Run or a named one and pumps. :fix is Fix and Continue: it rewinds a Run and reloads with its declarations in place, keeping the mailbox (ADR 0072); at a debugger pause it takes the paused Run, and the Host tells transcriptEnds where the Transcript stops. :runs, :mailbox and :vars render inspect(), so each is a vars Host Input.
  • Saves, Libraries and export: :save keeps the Group’s save with the Session Host’s own state in memory, and :restore restores it with RejectMismatch and adopts every pending call. :library compiles a user Library from a file (the environment’s readFile) or from the source lines a Transcript records, at version 1. :export prints the session source, or writes it and each user Library through the environment’s writeFile. A Transcript’s Trace Case setup adds each user Library as it was added.
  • Built-in Capabilities: :grant <name> clock grants the Standard clock, which reads the Pump’s Clock and costs nothing, so it needs no ~ answers.
  • Recording: the environment’s record receives the session as its Transcript records it: each Entry and Session Command in its recorded form (:clock virtual with its instant, :library with its source lines in place of its path), each real Clock reading before its Pump, each line typed for read, and each line printed. replayTranscript compares what the replaying Session Host records, so the corpus checks the recorder too. The northtalk REPL writes it with --transcript.
  • Built-in calendar and locale: offered to :grant when the environment’s builtIns supplies their Host functions, bound to the zone or tag :grant gives, or UTC and und. Each answer, or failure with its code, message and fields, is recorded as the call’s ~ line, and replayTranscript answers each call from those lines in place of a Host. The REPL’s are @northtalk/tooling/builtins.
  • Going on live: replayTranscript’s live option names the Clock, built-ins and recorder the Session Host turns to once the Transcript runs out, so a Host can continue a replayed session.
  • For tooling: started, sessionGrants (the Grants a Host Manifest is built from, without starting the session) and placementsOfSource (the code unit and line each declaration of the session source was loaded at) are outside chapter 12. debugController() gives the debug controller of the session’s Group once it has started. A Pump it pauses leaves waiting as paused, refuses input() and read(), and continueDebug(action) returns the Pump’s lines once it completes, exactly as it would have printed them unpaused; the Transcript and the Trace are unchanged.

The live debugger maps source breakpoints and supplies the adjusted Clock over these hooks; its Bun CLI runs a Script from a clean checkout.

group.debug() returns the Group’s TS-only controller; its types are available from @northtalk/ts/debug. This is outside chapter 9’s embedding interface and Trace parity, like the Session Host’s internal observation hook (ADR 0045). It adds no Host Input, Trace line or Fuel charge. Its state and the lowering’s statement-start metadata are absent from saves and Group Fingerprints; a restored Group starts with a fresh controller.

  • sources() returns detached loaded CodeUnits and their statement-start instruction indices, including Script extensions and Libraries. Replay uses these exact lowerings to rebind source breakpoints after lifecycle inputs and to find reverse statement boundaries.

  • breakAt(instructions) replaces the breakpoints. Each instruction is { pc, unit?, script?, run? }: pc is its zero-based instruction index, unit selects its code unit, script optionally selects the running Script, and run selects a particular Run id. Omitting a selector matches any. clearBreaks() removes them.

  • pauseOn({ error?, limitFault?, uncaughtError? }) replaces the fault-break settings. With error, every Error, caught or uncaught, pauses before unwinding; with uncaughtError, only one that no catch or guard in any frame covers, still before unwinding, so a catch whose tests all decline doesn’t pause; a Limit Fault pauses before rollback. current and the paused callback carry the reason, Run id, Script, unit, Handler, pc, line and column, plus the Error Value or Limit name for a fault.

  • A pause retains the current Pump and stops the whole Group. isPaused distinguishes it from a Fuel Slice. While paused, pump() and other Worker calls are refused as reentrant calls. The call that pauses returns a provisional { state: "sliced", fuelUsed: 0, reports: [] }; it has not completed a Pump or written pumped. Use the final result returned by resume() or a stepping method once isPaused is false. A callback can read the snapshot and queue Host Inputs, but must return before resuming or stepping. A callback that throws leaves the pause available for recovery.

  • snapshot() is available only while paused. It uses the internal state-reading path shared with inspect(), without calling that Host Input. It gives the same Scripts, Variables, mailbox and Run statuses, adding each Run’s Segment number, lifetime Fuel, whether it is rewindable and the repeated calls and sends a Rewind would leave done (ADR 0068), and frames with source positions and named local Values. During Recovery Offer dispatch, frames add optional role: 'retained' | 'dispatch'; a dispatch frame’s owner is the zero-based index of its ultimate shared-local owning frame in that Run’s view. Both display the same current owner locals, including writes made by policy or cleanup. Ordinary frame views and chapter 9’s Inspect schema are unchanged. Returned collections are detached views; Values are immutable.

  • resume(), step(), stepOver() and stepOut() continue the retained Pump. Stepping pauses only at statement starts recorded during lowering; explicit breakpoints and fault breaks remain active in every Run. Step over and out follow the active control path: a catch-test, policy or cleanup cursor replaces its owner at that call depth, excluding retained failed callees. Step over follows the same Run through a suspension and its later Pump. Step into follows a waiting send or foreign Function Value call into its receiving Run; step out of that Run follows the waiting caller. Steps that have not reached their target when a Pump finishes remain armed for the next Pump.

  • evaluate(body, frame?) runs a Handler body in the paused Run’s Script while the Group stays paused (ADR 0147). The body is compiled as an unapplied extension: Script Variables read and write as in any of the Script’s Handlers, and the named locals of the paused Run’s frame frame (an index into the snapshot’s frames, the innermost by default) arrive as parameters that the body can’t assign. It runs at once, alone, with up to 1,000,000 Fuel, and gives { value } or { error, line? }. A send, wait, random draw, Operation call or assignment to a local fails it. It writes no Trace line, queues nothing and draws no random number, so the Trace differs only where the paused Run reads a Script Variable the body wrote.

  • pausedTime() reports cumulative paused wall time in milliseconds, using a monotonic clock and including a current pause. A live debugger Host subtracts that duration from its Clock readings; the Core does not change the Host’s readings itself.

  • landAt(hostInputIndex, pc) arms a replay pause before the selected instruction. pc is a number, or the same instruction selector as breakAt; hostInputIndex is the replay driver’s zero-based Host Input index, returned in the pause event for that driver to identify the input. At that pause the driver queues the recorded Stop, CancelRun or RewindRun, then resumes. The input lands before execution and its Trace line includes pc, as it does for one queued at any live pause.

  • pauseAtNextStart(script) pauses once, as a step, at the first instruction of the next Run of that Script to start. Fix and Continue uses it after its Reload. The Trace Case runner handles these inputs in both replay modes.

The hook controls execution and reads state; it does not edit Script Variables or code. The debugger transport and UI live in the separate tooling stack. The tests in tests/debug.test.ts pause at instructions and faults throughout every Corpus Trace Case and compare the complete Trace in ordinary and save/restore replay.

Object element references: element s of receiver, ordinal references and the number of elements of receiver read an ObjectKindDef’s optional elements collection, as the contract says, with get-element, count-elements and prop crossings in the Trace. The Host Manifest writes the declaration. The WASI adapter declares a collection only to a guest offering object-elements-v1, and answers its prop needs with an op; the Zig reactor does not offer it yet.

Metering support: Operations may declare metering: 'read-only' (immediate or suspending) or metering: 'segment-bound' (immediate and segmentBound), validated at definition and carried by Operation Data, the Host Manifest and the Group Fingerprint, as the incremental metering contract says. A suspending read-only call may queue call.requestCharge(fuel), which returns the Group-wide request id (q1, q2, …) and a result Promise settled at the end of the Pump that processes it, beside a charge result report. The Pump drains requests in input order: accepted spends the Fuel at once, limit ends the Run with a Fuel Limit Fault at the call (a Join Member at its own) with no Stretch, and a call no longer pending gives inactive. Issued calls keep their eligibility for the Group’s lifetime, and the request counter and eligibility are saved; a pending metered call or unresolved request refuses Save with effects pending. Tests cover these, and the WASM tests check the same Trace from the Zig Core. A metered Operation’s callback that has a charge refused writes charge-refused=yes after the accepted charged in its call record, even when the callback suppressed the refusal; an unmetered one keeps the record without it. Trace Case replay reads the metering setup key, charge-request inputs and charge-refused Stubs.

createCore() returns the process-wide Core from chapter 9: Capability and Object Kind definitions, the Standard Capability factories, with peerKind for the peer Capability’s Peers, Library compilation, Group creation and restore. Existing free-function helpers remain available and share that Core’s definitions and compilation caches. Script code is cached by code identity across Groups, reloads and restores, while each load still checks its Grants, Object property declarations and limits and initialises separate Script state. Extension code is cached by the complete extended Script identity, since its bindings and variable slots depend on earlier definitions. Library compilation already shares code by identity; its Host version remains metadata.

exportManifest({ kind, version, grants, libraries, messages, objectKinds, objects }) returns compact JSON with one trailing LF for the Host to write to <kind>.talk-manifest.json. Optional collections default to empty arrays. Declarations, receiving kinds and parent kinds are sorted in code-point order; argument Shapes, map fields and alternatives retain declaration order. Properties include name, shape (default "value"), readOnly, getCost and setCost (default zero Fuel and allocation). Operation Declarations use the same data helpers as saves and Group Fingerprints, with non-empty plain-text description and source-text examples appended only in the manifest. defineCapability validates these fields; rewording them leaves saves, restore matching and Group Fingerprints unchanged. Bindings, native objects and executable Host callbacks never appear, and export never calls them. The manifest is tooling-only and outside Trace parity.

Script.extend links earlier code through private unit keys, so Host-chosen Script names containing colons, dots or slashes preserve inherited Constants, functions and parameter defaults across successive extensions.

@northtalk/ts/wasm is a Host Adapter that offers this package’s embedding API over the Zig Core’s wasm32-wasi reactor and its Message Layer, so a browser Host can run either Core (ADR 0097). Its Values, Shapes, errors and Capability and Object Kind constructors are this package’s own, so a Host switches Cores by its import. Both packages export the same Core, Group and Script interfaces, which the TS Core’s TsGroup and TsScript and this adapter’s WasmCore, WasmGroup and WasmScript implement (ADR 0121); tests/embedding-api.test.ts holds them to talk.ts, and the two packages’ exports to each other:

import { createCore, shape, text } from '@northtalk/ts/wasm'; // or '@northtalk/ts'
const core = await createCore(); // or createCore({ wasm: url, bytes or WebAssembly.Module })

createCore compiles talk.wasm, by default the file beside the module. Build it with zig build -Dtarget=wasm32-wasi in impl/zig, which writes zig-out/bin/talk.wasm, and serve it with the bundle. Every call after createCore is synchronous, as on the TS Core. The core-switch example runs one Host on both Cores.

Each Group has a guest instance of its own, with its own Instance Owner. Grant bindings, Host Objects’ natives, Operation functions, lifecycle hooks and futures stay in JS, and the guest’s interim needs call them. The facade negotiates seven features, and refuses a reactor that lacks any of them:

  • paused-inputs-v1, so a callback can queue calls.
  • abandoned-before-needs-v1, so a Call’s signal aborts before the next callback runs.
  • crossing-trace-v1, which brings refused calls’ Trace records.
  • climb-v1, so a Request settles at its answer.
  • function-gone-v1, so a stale Function Value call rejects.
  • standard-refinements-v1, so the Standard Capability factories are this package’s, with the guest’s own checks.
  • restore-bindings-v1, which rebinds Grants during a restore.

The optional request-pump-fields-v1 feature selects ADR 0110’s binary Request, Function-call and Pump envelopes. Each exchange retains its own final-reply format across nested callbacks. Guests without the feature keep ordinary JSON operations and refuse combined calls before admission. A combined Request registers cancellation before transmission, uses a Session-unique token during callbacks, then installs the delivery id before publishing final observations. An already-aborted signal is ordered as admission, cancellation and one Pump on the negotiated guest.

The independently optional callbacks-fields-v1 feature moves Operation, property, effect and Grant release needs and results to the binary fields envelope. It is requested by default, including when Request/Pump binary is unavailable. createCore({ wasm, binaryCallbacks: false }) keeps JSON callbacks for compatibility and performance comparisons; guests without this feature also retain JSON callbacks. Trace and resolve needs and their answers stay JSON. Nothing setters, failure Data, charge accounting and crossing notices keep the same meanings in either layout. Binary results use Values directly and defer their JSON Value Encoding until a JSON frame needs it. The local measurements show a Node speedup and a Bun slowdown for immediate-call and property workloads; measure the layout against the Host’s own workload.

It differs from the TS Core in these ways:

  • Making the Core: createCore is asynchronous and takes { wasm, diagnostics, binaryCallbacks }. Use core.versions, which both Cores have, rather than coreVersions: the language, Cost Model and Unicode versions match the TS Core’s, and the Core and save format are Zig’s. Use the Core’s methods: the package exports no free newGroup, restore, compileLibrary or defineCapability.
  • Saves have no native TS source-mode options or scriptSources callback and are in the Zig format, so neither Core restores the other’s (ADR 0008).
  • Libraries and Object Kinds must come from this Core’s compileLibrary and defineObjectKind, so it can declare them in each guest. A Library compiled elsewhere is refused with invalid value.
  • Each Group costs a guest: about 2 MiB of linear memory and 150 KB of JS heap (figures). Nothing caps a guest’s memory. A trap or an unreadable reply throws InstanceLostError and loses only that Group. Group.memoryBytes() gives its linear memory.
  • Frames are at most 64 MiB. A larger one, such as a save restored past that size, throws FrameRefusedError and leaves the Group usable.
  • Function Values that the guest makes read only homeScript() and their display form, and compare by the guest’s token. Text Patterns from the guest carry only their source. Both go back to the guest unchanged.
  • call failed details: a result the guest rejects, against its Shape or its error catalogue, reports Host result rejected by the Core, not the TS Core’s description. Parity covers the code, not the detail.
  • Not provided: save(options), the debugger hooks, the Session Host, the notification router and the subpaths other than @northtalk/ts/driver, whose helpers take this Core too.
  • keepMailbox on restore is sent to the guest, which ignores it until the Zig Core implements it (#1822): a Partial Restore there still drops each changed Script’s mailbox.
  • A Join of exactly maxJoin members faults under crossing-trace-v1 (#1128).
Terminal window
(cd impl/zig && zig build -Dtarget=wasm32-wasi --prefix ../../.cache/zig-wasi)
bun test tests/wasm.test.ts examples/core-switch # the same Host code on both Cores
bun tools/wasm-corpus.ts # every Trace Case, through the facade
bun tools/cross-core.ts # every save restored on each Core
bun tools/wasm-browser.ts # both Cores in headless Chromium, with figures
bun tools/request-pump-browser.ts # TS transfers and WASM callbacks in real workers
bun test tests/wasm-runtimes.test.ts # callbacks and Trace Cases, Bun/Node × binary/JSON

wasm-corpus.ts replays each Trace Case with this package’s Host side and the reactor behind it, in both replays. Its --json-callbacks flag retains the compatibility layout. It reports a known divergence with its issue, and a case whose save is past the frame limit, apart from failures. cross-core.ts is chapter 11’s cross-Core replay: it replays each Trace Case on both Cores, restoring every save on the Core that took it and on the other. It requires the same Trace, byte-identical saves from both Cores, and a save of each restored Group that equals the one it came from apart from the save id counter. wasm-browser.ts finds Chromium through --chrome, $CHROME or Playwright’s cache. Its --serve flag serves the pages for a browser of your own instead.

@northtalk/ts/message-layer exports encodeBinaryValue/decodeBinaryValue and encodeBinaryFrame/decodeBinaryFrame for the selected fields envelope. Encoders return dedicated ArrayBuffers suitable for postMessage(buffer, [buffer]); neither codec imports WASM or Node. Value options supply owner-specific Object and Function resolution, Function payload encoding, and negotiation of Core error markers and six/seven-item Function metadata. Metadata is validated before resolution. Value containers use heap traversal, including 20,000-level Values; decoding rejects noncanonical numbers/text, duplicate keys and trailing bytes. Decimal scale and Map insertion order survive.

Frame codecs take and return ordered Message Layer JSON nodes (JsonObject, JsonNumber, readOrderedJSON, also exported by the subpath). They preserve exact integer/decimal text and adapter Value tags; they do not execute messages or negotiate for a transport. A Host negotiates request-pump-fields-v1 through JSON hello before sending Request/Pump binary frames. Callback needs/results use the independently negotiated callbacks-fields-v1; other needs and their answers remain JSON.

Frame tags, field order, kinds, required fields and Report schemas come from src/generated/envelope.ts, written from spec/data/envelope.toml. The shared frame vectors check all four codecs against reviewed decoded trees and exact re-encoded bytes.

The shared vectors run against Go, Zig and TS. bun impl/ts/tools/request-pump-browser.ts from the repository root verifies those vectors in Chromium, transfers buffers both ways to a worker running the TS Core and executes a combined Request. A second worker runs the WASM callback Host in both binary and JSON modes and compares its Values, effects, release hooks and Trace. Use $CHROME for a custom Chromium executable. Folio’s application messages retain structured clone; these correctness checks establish no browser performance benefit.

Each Operation’s do, run, start and fire take their arguments in the JS forms of the declared args Shapes, and TypeScript infers the types from the literal (#1420, ADR 0120):

Shape Argument Result may also be
text string
bool boolean
number Decimal bigint
bytes Uint8Array (a copy)
instant bigint epoch microseconds
nothing null undefined
object(kind) HostObject<N>
optional(s) s’s form, null for Nothing, absent when omitted undefined
any other Value

A result may always be a Value, and call.answer takes the same forms as a result. The Core converts a JS result before checking it, so a JS form the Shape doesn’t name fails as a wrong result. Conversion makes a run answer settle one microtask after its Promise. Ops built at run time with Shape[] type their arguments unknown. The Core’s own Capabilities keep the Value-form defineValueCapability, which the package doesn’t export.

For a suspending Operation, retained call.answer and call.fail methods continue to queue inputs after the call ends, including after timeout, Stop or Reload. The next Pump records each late reply as note … kind=late-answer and ignores it, without charging late answer Fuel or resuming the Run. group.settle resolves pending calls from a restore before its first Pump; its unknown call refusal outside that window does not apply to these ordinary replies. Regression tests cover late replies after settlement and teardown.

defineCapability(name, operations, lifecycle?, release?) (or defineCapability<B>()(...) with a binding) accepts an independent, synchronous release hook with GrantContext: Group instance, Script and named Grant, binding, last Clock reading and reason stop, reload, revoke or disable. This follows the Grant release contract (#618). Stop, owner disposal and fatal effect uncertainty release kept Grants in code-point name order after abandonment and rollback, before the Stop report. Successful Reload and Library replacement use reload, including Grants already revoked or disabled; rejected updates, Extend, Save and Restore release nothing. Revocation releases once when drained, and failed automatic abandonment releases immediately after its effect failure report.

Library replacement completes abandonment and rollback for every affected Script before releasing any Grants with reload. If a rollback leaves effect state unknown, the Group stops and releases its Scripts with stop, keeping the previous code.

Hooks spend no Script resources and add no Trace records or Manifest/Fingerprint fields. They may queue Host Inputs; worker calls are reentrant call. Throws are ignored and do not prevent subsequent Grants from being released. The embedding tests in tests/grant-release.test.ts cover lifecycle order and identity. This Core has no Message Layer adapter; its release transport tests are deferred, while the Go adapter carries the exchange. The store factory forwards its implementation’s release hook; see the router below.

peerCapability forwards an optional release method on its PeerImpl the same way; an implementation without one needs no change. PeerRouter’s impl.release withdraws the exposures a released Grant made, named and unnamed, and frees each name still held by them: on stop, owner disposal included, and on revoke and disable. A successful Reload keeps them, as chapter 7’s peer Lifetime says. An exposure’s owner is its Group, Script and named Grant, so expose, unexpose and release compare all three. A Request already delivered runs on. The router has no restore path of its own yet, so a restored Group’s exposures are the Host’s to set up again.

A Host that keeps musical time, such as Folio with its Transport, gives the Group a musical clock, so a Script’s wait 8 bars or wait 2 beats ends on the Host’s bar or beat line rather than after a fixed duration (chapter 9, ADR 0166):

const clock = core.musicalClockCapability(
{
// `count` is the Quantity the Script waits for: a whole number of bars
// or beats, 1 or more. Answer on that line, one lead early if you like.
wait: (call, count) => transport.onLine(count, () => call.answer(nothing)),
},
{ wait: { fuel: 1 } },
({ scriptName, reason }) => transport.forget(scriptName, reason), // optional
);
const group = core.newGroup({ name: 'song', musicalClock: clock });
  • Ending a wait: answer the call with Nothing (call.answer(nothing)) when the line is due, or call.fail(...) to raise in the Run. Stop, Reload, cancellation and a Timeout Block abandon it, aborting call.signal; the call has no maxPending, and MaxWait doesn’t apply.
  • The reserved Grant: every Script holds the clock as the Grant musical-clock, which no source can name. Script.grants() leaves it out, revoke ignores it, grantsAsUsed keeps it, and a Host Grant of that name is invalid value. Its calls appear in the Trace as op=musical-clock.wait, the release hook gets its stop and reload calls, and the Group Fingerprint includes its declaration.
  • Only the Core makes one: wait can’t name a Host’s Operation, so musicalClockCapability is the only way to make the Capability the musicalClock option takes.
  • Saves: a pending musical wait is a pending call. Pass musicalClock to restore too, and settle the restored call as any other: reissue starts it again on the new clock.
  • Without one, a wait in a Musical Unit raises no musical time; wait 0 bars goes straight on either way. exportManifest({ musicalTime: true, ... }) tells tooling the Host keeps musical time.
  • The Zig reactor: @northtalk/ts/wasm takes the same option. It grants the clock as musical-clock at load and restore, and declares it to the guest with musicalClock: true on define-capability.

Trace Cases supply one through [[standard]] with capability = "musical-clock", and end each wait with answer or fail inputs, as in corpus/musical-time/. The tests cover the rest.

@northtalk/ts/http supplies createHttpHost(options), the HTTP router for the optional http Standard Capability (ADR 0124). It serves on node:http and runs under Bun and Node. Give its impl to httpCapability, and call pumped(group, result) after each Pump, as onPump(group) does for a driver. It keys Serve Registrations by owner (Group, Script, named Grant) and name, shares a listener per host and port, matches the longest prefix, delivers each request as one Script.deliver and answers what the Script didn’t from the Pump’s reports. allow(host, port, binding) refuses addresses with bad address; defaultHost is 127.0.0.1 and defaultPort 0; portOverride moves every serve. A body over maxBodyBytes, 1 MiB by default, is answered 413 without a Delivery. detach(group) answers a discarded Group’s open exchanges 503; stopAccepting(), drain(ms) and close() shut down gracefully. The http test kit holds it to the Spec through tools/http-kit.ts.

The client Operation, fetch (ADR 0151), comes from createHttpFetch(options) alone, for a Host that only fetches, or from createHttpHost({ fetch: options }) beside serving. Its origins are 'any', a list of exact origins such as ['https://api.example.com'], or a function of the Grant’s binding giving one; the default, an empty list and an undefined result allow none, and a refused origin is bad address. A list that isn’t exact origins throws invalid value when the factory is built. It requests with node:http and node:https, one connection per call: it sends accept-encoding: identity unless the Script set one, never decompresses or follows a redirect, sends no ambient cookies, verifies TLS against the runtime’s authorities or ca, bounds the body to maxBodyBytes (8 MiB) and the headers, trailers included, to maxHeaderBytes (64 KiB) with response too large, aborts when the call is abandoned, and fails anything else with network error. It doesn’t check the addresses a name resolves to. The Script Runner allows any origin.

@northtalk/ts/notify supplies createRouter({limits, revision}), the notification router (#619). It holds watches by owner (Group, Script, named Grant) and name, routes each commit(store, apply) to matching watches as ordinary Script.deliver Deliveries, holds what MailboxFull refuses within the Store’s four limits, falls back to one Reconciliation Marker on overload, and retries fairly from pumped(group). release and detach remove watches. save(group) writes a checkpoint: a header, the routing state as one JSON line with the save’s SHA-256 and each watched Store’s revision, then the Group.save bytes. restore(core, checkpoint, options) refuses anything else as invalid checkpoint before calling Core.restore. changed(before, after) is the net-change test a Store uses to compute a commit’s changed keys.

The router uses only the embedding interface, plus Group.scriptNames(), which reads Script load order inside a Pump with no Trace record. It runs under Bun and Node. tests/notify-kit.test.ts runs the router kit on stand-in Groups, tests/notify-runtimes.test.ts runs it under Node, and tests/notify.test.ts drives it with real Groups. Memory, Web Storage and SQLite-backed Stores route commits and Host replacements through their router. Hosts call router.pumped(group) after Pumps, detach(group) on discard, and save/restore for companion checkpoints. Watch limits default to the Session limits; new Stores(backend, quotas, watchLimits) overrides them. Web Storage notifications remain local to one engine; sharing its contents between tabs is unsupported. The Session Store accepts watching with costs 4/2 and limits 100 watches, 65,536 watch bytes, 1,000 pending Notifications and 1,048,576 pending bytes. createRouter’s optional admitted(group) is told after each Notification a Group admits, and memoryStores(quotas, admitted) passes it on. The Session Host uses it to pump again at the same Clock reading while Notifications are queued, retries with pumped after every Pump, keeps checkpoints for :save/:restore and detaches a Group it replaces. A Host call that leaves other Host Inputs queued gets one more Pump of its own; see tests/session-pumping.test.ts and the sessions/store-notif* Transcripts.

Immediate Operations support scope: { opens, abandon } and scope: { closes } from the lifecycle contract. Grant the abandonment Operation along with its opener; grantsAsUsed retains this dependency. Host Calls identify resources by group instance, scriptName, runId, grantName and scopeName, with segmentId identifying the current Segment.

Run termination attempts remaining abandonment in reverse opening order, after plain-scope Script finally blocks where those run. Automatic Calls use automatic: true, a fresh signal and no Script budgets; their charge, answer and fail methods are unavailable. Failure emits an effect failure report and disables that named Grant. inspect().scripts[].disabledGrants exposes disablement, which survives Reload, Library replacement and both Restore policies. A fresh Script load is the recovery boundary.

An open scope prevents suspension-producing boundaries and Join entry, while Fuel Slice preemption still works. Lifecycle guards run after operand/Grant validation and instruction-specific limits, before the instruction’s Fuel and allocation charge. Rejections still pay Handler dispatch and ordinary unwind costs. Save refuses live scopes and participants with effects pending.

Immediate Operations may declare segmentBound: true when defineCapability(name, operations, lifecycle) supplies synchronous begin, commit and rollback hooks, or a { coordinator(binding) } mapping to a Segment Coordinator holding them. grant resolves the mapping once, and the Grant keeps that coordinator through Reload and Restore; a plain lifecycle makes each named Grant its own. Each hook receives SegmentContext with Group identity, Script, Run, Segment, last Clock, the first enrolled Grant’s name and binding, and grants, every enrolled Grant in enrollment order; it returns EffectResult with status ok, failed or unknown and optional Host-only detail. Lifecycle Operations of one scope must agree on segmentBound. One coordinator participates per Segment, including across preemption: begin runs at its first Segment-bound call, later Grants of the same coordinator (compared by identity) enroll with no hook, and a Grant of another coordinator, or a plain-lifecycle alias, raises segment participant conflict naming the first enrolled Grant. Failed abandonment on any enrolled Grant prevents commit and disables only that Grant; cancellation abandons scopes on every enrolled Grant before rolling back. The store factory maps every binding to its implementation as one coordinator. Segment ids are <run>.s<N>, advancing at actual suspension and cancellation cleanup boundaries.

The Core finalizes after Script charges and Persistent State checks, before replies, forwarding, Verdicts or suspension publication. Completion and ordinary errors commit; Limit Fault, Stop and replacement roll back. Remaining scopes abandon before finalization, and an explicit scope close stays provisional. Cancellation abandons participating scopes and rolls back first, then runs Script finally in a fresh cleanup Segment while unrelated scopes remain available.

Definite commit failure or failed participating abandonment rolls back Script Variables and ends the Run as uncatchable effect failed, with an effect failure in its report. Unknown outcomes and unsuccessful rollback stop the Group with effect state unknown; Load, Reload, Extend and ReplaceLibrary cannot resume it, and Save refuses it. Reload and Library replacement validate prospective post-rollback carried variables before terminating old Runs. Hooks cannot reenter worker calls, and have no Script cost.

Messages, property writes and unrelated immediate effects remain outside this guarantee. There is one participant per Segment, synchronous lifecycle work and no crash recovery. Lifecycle and failure Trace records expose hook ordering. Reload and Library replacement return cleanup reports even when fatal uncertainty stops the Group and prevents replacement; subsequent attempts to change that Group receive effect state unknown. The recording-Host tests in tests/scopes.test.ts, tests/segment-effects.test.ts and tests/scoped-integration.test.ts verify ownership, provisional/committed state, native reports and exactly-once attempts. tests/scoped-conformance.test.ts runs every shared scope/Segment-effect case in normal, automatic save/restore and recorded-result replay. Live-effect Save attempts must refuse without changing execution; replay continues the original Group there. The coverage reconciliation maps every chapter 11 scenario to executable cases or Host tests and records the Message Layer transport gap. The Traces await first human review. Thirteen scope cases agree with Go, including the corrected guard charges; Go runs the Segment-bound effect cases too; see its Segment-bound Operations. Production Message Layer conformance is not claimed.

Under Bun, import from the package:

import { text, num, list, map, encodeValue, readDisplay } from '@northtalk/ts';
const title = text('e\u0301'); // NFC: é
const values = map([
['title', title],
['count', num(1)],
]);
console.log(values.toString()); // {title: "é", count: 1}
console.log(encodeValue(values)); // {"title":"é","count":1}
console.log(readDisplay(values.toString()).equals(values)); // true

The implemented portion of the embedding declarations is HostError, Value, Decimal, nothing, bool, text, num, dec, list, map, record, quantity, bytes, instant, civilDate, range, encodeValue and decodeValue, plus readDisplay, the display reader required by chapter 11. Implemented kinds are Nothing, booleans, numbers, Quantities, text, Bytes, lists, maps, ranges, Instants and Civil Dates. quantity(dec("2.50"), "GBP") takes a number and a Unit spelled as a Script spells it, and asQuantity() reads back the number and the Unit in normal form. A Quantity is {"$quantity":["2.50","GBP"]} in the Value Encoding, with every word Unit singular, and a range {"$range":[from,to]}. bytes(u8) copies a Uint8Array in, and asBytes() copies one out. Bytes display as <<0x0D, 0x0A>> and encode as {"$bytes":"DQo="}, canonical padded Base64. instant(epochMicros) takes a bigint of epoch microseconds, and civilDate takes fields or text in the as civil date form; both refuse dates outside 0001-01-01 to 9999-12-31. They encode as {"$instant":"2026-09-27T13:30:00Z"} and {"$date":"2026-09-27"}. Value supports the accessors for those kinds, structural equals and display-form toString. Construction is opaque; invalid inputs throw HostError with code invalid value. decodeValue resolves a Host Object through the supplied kind/id resolver. Unsupported kinds and tags are refused explicitly.

value.asText() returns the text payload only for a text Value, and undefined for every other kind, including numbers. String(value) gives any Value’s display form, with text in quotes; fromValue(value), below, converts it to JS data:

import { fromValue, num } from '@northtalk/ts';
const answer = num(10);
console.log(answer.asText()); // undefined
console.log(String(answer)); // "10"
console.log(fromValue(answer)); // Decimal
console.log(fromValue(answer, { numbers: 'string' })); // "10"

toValue(plain) and fromValue(value) convert plain JS data by ADR 0119’s table, using the constructors and accessors above. toValue({ id: 'a1', qty: 3n, tags: ['x', null] }) builds the map, with null and undefined as Nothing. A JS number is refused by default. With { numbers: 'integer' }, safe integers pass through num; fractional, unsafe and non-finite numbers throw invalid value naming dec() and { numbers: 'decimal' }. With { numbers: 'decimal' }, numbers follow num’s shortest round-trip rule. fromValue gives null, booleans, strings, Decimals (or canonical strings with { numbers: 'string' }), copied Uint8Arrays, arrays and plain objects (or Maps with { maps: 'map' }). It returns every other kind as the Value, and toValue passes a Value through unchanged.

decodeValue accepts only the canonical numbers, tags and payloads that encodeValue writes, and throws HostError with code invalid value for other forms. An integer with no fraction digits and magnitude below 2⁵³ must be a JSON number, so {"$dec":"3"} is refused; a map without a key starting with $ must be a JSON object, so {"$map":[["a",1]]} and {"$map":[]} are refused. JSON white space and string escapes remain accepted, and text is normalised to NFC. Store files, SQLite Store values and Session Object recordings use the same decoder. A save’s values are binary (chapter 10, The save format), and a value no Core writes is invalid save.

Text is checked for lone surrogates and normalized to NFC at construction. Lists and maps snapshot their input; map keys are normalized, checked for duplicates and kept in insertion order. record refuses JS array-index keys; use map to specify their order. Number constructors retain trailing zeros, expand a float’s shortest round-trip digits and refuse values requiring rounding or exceeding the spec’s limits. Decimal supports canonical text, exact integer reads and lossy float reads. It also caches an immutable BigInt coefficient, exponent and sign for arithmetic, comparisons and Cost Model measures; arithmetic results retain those parts directly and readers rebuild them. Canonical text still determines display, Number equality and Value Encoding, and the save format is unchanged. Arithmetic is implemented by the decimal operations used by the Abstract Machine.

Arithmetic results build and cache their canonical text on the first read. Digit counts use a numeric estimate corrected by exact BigInt comparisons with powers of ten; large intermediates use a power-of-ten search. Unit conversions skip exact identity factors when the decimal already fits the value limits, retaining the ordered arithmetic for every other factor and for inputs that still need rounding. These caches and shortcuts preserve trailing zeros, Fuel, logical allocation and the Trace.

Integer-range iteration derives its start from the cached Decimal parts and builds items through the checked internal integer constructor. A weak cache keyed by the immutable range keeps that start outside saved state; restored sources rebuild it on their first Next. Iterator source, position, Fuel and logical sizes retain their chapter 8 representation.

Value and Decimal keep their state in private fields and prevent extension, so a Host cannot replace their accessors or shadow kind. Map storage owns its pairs and shares them between persistent versions. Host reads through entries() or mapPairs() copy both the outer array and each pair; the Cost Model reads the owned pairs through an internal module function. Instruction charging reuses Run-local scratch without changing Fuel, logical allocation or saved state.

Exact terminating division and bounded integer quotients bypass general rounding; remainders use one operand alignment and already fit the precision bound. Division that needs rounding retains the general half-even path, including subnormals and overflow checks. These paths preserve the operator’s ideal exponent and trailing zeros.

src/unicode.ts and src/text.ts provide internal foundations for Character segmentation, simple folding, default full case mapping (including final sigma), scalar ordering, NFC joins, whole-Character literal searches, and character/code-point/word/line/item splitting. They are not additions to the public embedding interface. They charge no Fuel outside a Run; the Abstract Machine must charge Cost Model 0 when it calls them. This slice adds no language-level execution or resource-accounting claims.

Text Values keep their ASCII flag, UTF-8 length, Character count and immutable Character views in TextStorage. Concatenation adds cached measurements, correcting only the join for NFC and Character boundaries, including CRLF, flag pairing, emoji ZWJ and Indic linker context. A contiguous Character slice is already NFC and skips normalization. These caches are private derived data; they do not change Fuel, the Trace, Value Encoding or the save format.

import { parseSource, syntaxText } from '@northtalk/ts';
const result = parseSource('on greet\n say "hi" -- greeting\nend greet');
if (result.error) {
const { code, tok } = result.error;
console.log(`${code} at ${tok.line}:${tok.col}`);
} else {
console.log(syntaxText(result.tree)); // exactly the original source
}

parseSource accepts a complete Script or Library and returns either a typed concrete syntax tree or its first ParseError. Invalid scalar source throws HostError("invalid value") before parsing. The syntax tree is a Core front-end API; it is not an addition to the normative embedding declarations. Syntax checking here implements chapters 1 and 2; name and binding checks are described below.

Raw Text Literals preserve backslashes and placeholders. Backticks decode escapes and accept nested multiline Interpolation Holes. Both forms support exact closing margins and physical newline normalization; hole-free forms also work in literal-only Text positions. Holes retain Constant and Guard restrictions and lower to ordinary concatenation instructions, with generated joins mapped to ${. Invalid closing margins identify the first non-whitespace source scalar; paired Corpus cases also pin interpolation Fuel and allocation faults and Segment rollback.

For a file being edited, parseSourceRecovering(source) always returns a lossless tree for scalar source, together with error (the same first ParseError as parseSource, or null) and diagnostics. Each diagnostic holds { error, recovery }: the first has recovery: false, and every later syntax error has recovery: true. Only the first error is normative. Invalid scalar source still throws HostError("invalid value").

Recovery uses the same productions as the strict parser. Failed regions become Error nodes owning their partial productions and skipped tokens. Expression recovery resumes at a comma, closing delimiter, separator or physical newline; statement and declaration recovery resume at a physical newline. Incomplete blocks retain their parsed bodies at EOF or an enclosing branch or reserved declaration boundary. A missing ending can have a zero-width Error node; no token or source character is invented. syntaxText reconstructs the complete original input, including malformed regions. Recovery is best effort: malformed heads or delimiters can hide otherwise valid code, and later errors may follow from earlier ones. It does not make malformed source compilable or change parseSource, checkSource, parseEntry or compilation.

import { parseSourceRecovering, checkSyntax } from '@northtalk/ts';
const parsed = parseSourceRecovering(
'on greet name\n @\n return name\nend greet',
);
const checked = checkSyntax(parsed.tree); // Handler and parameter bindings remain available
// Show parsed.diagnostics before checked.diagnostics; all output after the
// first syntax error is tooling recovery, outside parity.

Each SyntaxNode identifies a recognition production with rule, ordered children, and half-open start/end spans. Its children are further nodes or Tokens. A token retains its exact raw spelling, pos/end, initial lexical mode, and leadingTrivia. Trivia records preserve the initial BOM, spaces/tabs, comments and continued physical line breaks; statement-ending line breaks and EOF are tokens. Spans include leading trivia, and every source character belongs to exactly one token or trivia record. syntaxText reconstructs source by walking the tree, without requiring a separate source string. Offsets index the original TS string in UTF-16 code units; diagnostic line and col are 1-based Unicode scalar positions, with tabs counting as one column. Text literal content remains as written; the existing text value constructor performs pinned NFC when a literal becomes a value.

The low-level Lexer is also exported. Call lex(offset, mode) at a token boundary; it returns the next physical token without applying statement continuation. where(offset) provides scalar positions. Modes are operand, operator, pattern, unit (after a number), and type (after as). The strict parser fixes each token’s interpretation on its first scan, buffers at most two tokens and never backtracks or relexes. After an error, recovery discards unconsumed lookahead and resets delimiter and continuation state before scanning physical tokens to a boundary. Productions run through an explicit work stack, so deeply nested source does not depend on the JavaScript call stack. Scalar column lookup uses indexes rather than rescanning long lines. It handles the full grammar, including contextual keywords, compound units, Text/Binary Patterns and block Lambdas inside brackets. No platform Unicode normalization or Host imports are used by the front end.

Terminal window
bun run syntax:generate
bun run syntax:check
bun test impl/ts/tests/lexer.test.ts impl/ts/tests/parser.test.ts impl/ts/tests/syntax-fixtures.test.ts

The generator copies the syntax lists from grammar.toml, Unit spellings and Unit Kinds from units.toml, and the instruction set from machine.toml into browser-safe TS tables. The check reproduces those tables byte for byte and runs in CI, tests and builds. Core tests independently exercise authored first-error fixtures, every corpus Script, Standard Library, syntax sketch and talk documentation example. They also check every token/trivia span and exact source reconstruction. These parser checks do not establish execution, lowering or Trace conformance.

Generated opcodes are individual constants, imported as a namespace by the interpreter so browser bundlers can inline their numeric values. Save/Restore and the Standard Capability factories remain available through the existing Core API. The bundle size profile estimates that splitting those features could save 12–13 KB gzip; that saving alone does not justify changing the public API without evidence that Hosts commonly omit them.

import { checkSource, checkSyntax, parseSource } from '@northtalk/ts';
const result = checkSource(
'on greet\n return later\n put 1 into later\nend greet',
);
console.log(result.ok); // true: later starts as Nothing
console.log(result.tree?.scopes); // unit and body bindings, including it
const invalid = checkSource('on greet\n return absent\nend greet');
console.log(invalid.diagnostics); // unknown name at line 2, column 9
const parsed = parseSource('constant answer = 42');
if (!parsed.error) checkSyntax(parsed.tree); // check an existing lossless tree

checkSource parses once and returns either the first syntax error, with no semantic tree or load diagnostics, or the semantic tree and ordered diagnostics. checkSyntax accepts an existing SyntaxNode without reconstructing or reparsing source. Both are front-end APIs, not additions to the embedding interface. ok means the implemented semantic checks succeeded; later load checks and compilation are still required.

Container parsing rejects Built-in properties anywhere on the target path, including in set, with not a container at the target’s first token. Parentheses preserve that path. Quoted/computed keys and property reads in key, index, delimiter and value expressions remain allowed.

it is a body local. In a Constant or Script Variable initialiser or a parameter default, each unbound it reports unknown name, alongside not constant at only the first disallowed token. Handler, function and Lambda bodies retain their own it, including Lambdas created at load.

On a recovered tree, checkSyntax treats Error regions as opaque and omits constructs with malformed operands or heads. Blocks keep their other statements, so parsed declarations, scopes, bindings and load diagnostics remain available to tooling. The lossless syntax tree is unchanged. These diagnostics are recovery output; ok only describes the retained semantic checks and does not mean the original source is valid. Consult the recovering parser’s error as well.

The typed semantic tree retains grammar productions and operator/literal tokens for later lowering, omits trivia and empty productions, and replaces declaration, binding and reference tokens with SemanticName nodes. Every node has a half-open UTF-16 source span and a 1-based scalar start position. Name nodes identify their role and resolved Binding; body nodes identify their scope. Scopes expose parameters, locals (including it), and Lambda captures in first-use order. Local bindings record their Nothing initialization. The input lossless tree remains unchanged. Conversion and traversal use explicit work stacks, including for deeply nested expressions.

Script and Library Load and compileSource use an internal compact tree from the same recognizer. A precedence production containing only another node, with no operator, contributes that child directly. Productions with operators, binding/scope boundaries and explicit Kinds remain present. This reduces the work of checking and lowering; public parseSource, checkSource, checkSyntax and recovering parsing retain their full trees. Diagnostics and emitted code are checked against the full-tree path across the lowering fixtures.

The checker collects unit declarations, parameters, destructuring/Capture bindings and Container roots before resolving value references and calls. Locals cover the whole body; branches, loops, catch and event branches add no scopes. Lambda scopes capture enclosing locals, including those needed by nested Lambdas; Script Variables remain live unit bindings. Built-ins may be shadowed, Script/Library function names are values, and Handler/Built-in function names require a call. A Script Variable or Constant may share a local Handler’s name in either declaration order: value references read the variable or Constant, while Command Calls select the Handler, including from a Script extension. Command Calls resolve local/imported Handlers or continue along the Message Path. Message, property, map-key, kind, Grant and Operation positions do not undergo value-name lookup. Binary Pattern bare sizes require a completed earlier field binding, while pins resolve body names.

Implemented diagnostics are unknown name, not a value, name clash, duplicate name, direct unknown import checks, can't write, not a property, wrong argument count, default order, not constant, outside a loop, leaves finally, not in a lambda, wrong message, bad suffixes, not in a script, not in a guard, duplicate key, bad number, unknown kind, no conversion, nothing to fold, no item chunk, capture in repetition, rest not last and bits not whole bytes. Duplicate checks cover parameter lists, destructuring and Text Pattern Captures; rebinding a local in a separate pattern is valid. Diagnostics use the token positions and tie ordering from diagnostics.toml, with one diagnostic of a code per offending token. Import clashes point to the local name in the use line, including a rename. The browser-safe tables include diagnostic order, Built-ins and Standard Library export kinds and function contracts, generated from the Spec Data Files.

Every Container write rejects a Constant root or a captured Lambda local at the root’s name. Imported Constants keep their binding when written, including through a rename. Script Variables and the Lambda’s own locals remain writable; writing a Built-in Constant’s name creates a local that shadows it. set on a bare variable reports not a property at set; Load, Reload and Extend also reject literal writes to missing or read-only properties of a well-known Object or owner me. Quoted and parenthesized Text literals count as known keys; aliases and other computed keys remain runtime checks. Each preparation rechecks its declarations before using cached code.

Named calls use the resolved binding’s contract: { required, total } to check argument counts, including forward and recursive calls, Built-ins and imported Standard Library functions. Function Values held in variables and Handler calls retain their run-time argument checks. Required parameters after a default report default order. Constant/Script Variable initializers and parameter defaults permit literals, earlier Constants (including imports) and Built-ins, and report not constant at the first forbidden reference or construct. Self and forward Constant references, Script Variables, parameters, user functions, me, it and the target are forbidden when evaluated by an initializer/default. Lambda literals defer their bodies; creating one is permitted if it captures no enclosing locals or parameters. Initializers and defaults are not evaluated by this pass.

A control pass walks the semantic tree after binding checks. Each Handler, function and Lambda body starts with no enclosing loop, finally block or Lambda context, so a Lambda’s return and loops are its own. exit repeat and next repeat report outside a loop with no loop in their body, and leaves finally when their innermost loop is outside the innermost finally block (of a try or a Handler) that contains them. return, veto and pass inside a finally block report leaves finally. pass and bare the target inside any Lambda report not in a lambda at pass or the, including Lambdas in initializers and defaults; the target of x is a key. Outside Lambdas, pass m in a Handler reports wrong message at m unless m is the clause’s message, compared case-sensitively. A Handler head reports bad suffixes once, at the first suffix that repeats one, adds a second of queued/dropping/replacing, pairs queued with deciding, or is during on a Handler other than on error. Join, decision and Library-only placement rules are covered by the later control passes described below.

The same pass reports not in a script at private unless { unit: 'library' } is passed, since private starts a declaration only in a Library. Each Guard (where on a Handler, when, catch or wait for branch, or a one-line wait for) reports not in a guard at the name of a call that doesn’t resolve to a Built-in function, including a name that shadows one, at a Lambda’s given, and at the the or 's that reads a key other than id or a Built-in property from me, the target or a well-known object. Known Objects with computed keys require the Text literal id, including nested parentheses. A dynamic Guard reads map keys or Core-held Object id; other Object keys, live or disposed, raise charged wrong kind (expected map) and skip the clause without calling the Host.

A construct pass walks the semantic tree for load rules local to one construct. Map literals report the second equal key, comparing text keys after NFC. Number literals past 34 significant digits, 10^34 or 6176 fraction digits report bad number, sharing the Host constructor’s limits. is a and is not a accept chapter 3’s kind names and integer; as and can be accept kind names and Units; any other name reports unknown kind, and as with a kind that has no conversion reports no conversion at as. ignoring case after a kind or emptiness test reports nothing to fold. delimited by reports no item chunk unless its chain of chunks, ordinal chunks and items properties includes an item chunk. In Text Patterns, a Capture inside n e, one or more of, zero or more of or optional reports capture in repetition (a splice starts its own pattern); a Typed Element other than a number reports unknown kind; and as number reports no conversion unless it follows a number or an element that always matches one or more ASCII digits. A list or Binary Pattern ... before another item reports rest not last. Each run of consecutive bit fields in a Binary Pattern or build whose integer-literal sizes don’t sum to a multiple of 8 reports bits not whole bytes at its first field.

Pass { objects: ['button'], libraries: { helpers: { double: { kind: 'function', contract: { required: 1, total: 1 } } } } } to either checker to supply well-known Host Object names and registered Library exports. Kind-only entries (function, handler or constant) remain accepted and defer function argument-count checks until the Library loader supplies a contract. Standard Library metadata is known by default; a supplied entry overrides one Library’s exports. The Group and Library loaders add graph/cycle checks, Grants, constant/default evaluation, effects, Suspension Point, Join, decision, Library-only and Text Pattern size checks. Supply objectProperties: { button: { label: false } } for known setter availability, and ownerProperties for me; the Group loader supplies these from registered Object Kinds. Standalone checking without declarations defers read-only checks. A successful standalone checker result does not establish that a Group can load or execute the code.

Terminal window
bun test impl/ts/tests/checker.test.ts

Core tests check exact authored codes, scalar positions, diagnostic ordering, bindings and capture identities, all binding forms, function contracts, initializer/default references, control flow across nested Lambdas, loops and finally blocks, Handler suffixes, Guards, literal, kind, chunk and pattern rules, and deep input. The browser smoke test also exercises name resolution, binding/function contracts, control-flow and construct checks with platform Unicode functions disabled.

Handler heads, Command Calls, target-first send, pass and wait for accept Argument Labels from grammar.toml’s [labels], as chapter 2 specifies. on move p to sq and move 1 to 2 name move:to:; positional move 1, 2 still names move. Selectors identify Clauses, Message Paths, wait events and their it, and Trace records. Host Deliveries, Requests, Broadcasts and Decisions reject malformed colon-containing names or mismatched argument counts at the call with invalid value. The pure syntaxSelector and validMessageSelector helpers expose the same syntax and Host validation rules to tooling.

send (e) with a to r computes its message name (ADR 0057). It lowers to send-named, send-named-wait or join-send-named, which pop the name below the arguments. The name is checked before the receiver: non-text raises wrong kind, and text that isn’t a Name or a Selector with one argument per part raises bad message name. A receiver Name for a Script the Group doesn’t hold raises object gone at the send, after that check.

on any message m declares a Fallback Handler (ADR 0064). Its clauses lower to fallback bodies named any message, which Code keeps apart from the Selector-keyed clauses, so Broadcast “want” and local Command Calls never see them. A Delivery that isn’t a Broadcast, a Decision or an error message tries them after its Selector’s clauses, with the map {name, args}, and its Run reports fallback with the Selector as handler. Queueing Policies key a Fallback clause by its number alone. A spread in send … with builds the arguments as one list under the name as text, and send-spread, send-spread-wait or join-send-spread pops the name, the list and the receiver, checking the name as send-named does.

An Operation declared command: true may also be called by its name alone (ADR 0094). defineCapability refuses the flag on a Reserved Word, and one that isn’t Boolean, with invalid value. The flag is part of the Operation Data, so the Host Manifest, the Group Fingerprint and restore’s declaration matching carry it, written only as true; saves keep the whole declaration.

After name resolution, the checker’s resolveHostCommands (in effects.ts) resolves each unlabelled Command Call that names no Handler of the unit, local, imported or from an earlier Extend, to the one Operation its GrantDecls mark command. It records the call in hostCommands and, for a fire-and-forget Operation without and wait, in toldLines, as a tell block’s line is. The view then reads the statement as that tell or ask, so lowering, Join and Decision checks, needs, GrantsAsUsed and import rechecks see an ordinary Operation call: hide x emits exactly what tell folio to hide x does, count what ask folio to count does, and fetch x and wait ask-wait. No instruction is added. Load checks report wrong mode, wrong argument count and wrong argument at the command’s name. Two Grants offering the called command, and an Import named like any offered command, are name clash, at the call and at the Import’s name. Without grants, as for checkSource alone, nothing resolves.

Since resolution depends on the Grants and not the source, a unit’s compile cache key (compileKey) adds its resolved calls to its code identity; the code identity itself is unchanged. A Command Call with and wait stays not in a join and not in a timeout even when it is a Host Command.

Terminal window
bun test impl/ts/tests/host-commands.test.ts
bun run corpus:run capabilities/host-commands
import { compileSource, disassemble } from '@northtalk/ts';
const result = compileSource('on greet name\n say "hi " & name\nend greet', {
name: 'greeter',
});
if (result.unit) {
console.log(disassemble(result.unit)); // chapter 8's canonical text
}

compileSource checks a Script (or, with { unit: 'library' }, a Library) and lowers it when there is no syntax error and no load diagnostic; otherwise unit is null. It takes the checker’s options, plus the unit’s name. lowerTree lowers an already checked semantic tree, and exportsOf gives a checked Library’s exports in the form the checker’s libraries option takes. The code unit holds chapter 8’s tables in order: the constant pool (as display forms), definitions, Script Variables, objects, the body table, one instruction array, the Unwind Table and the event table. Operands are indexes where the table has them and names otherwise, and labels are absolute instruction indexes. None of this is an addition to the embedding interface.

The lowering follows chapter 8 rule by rule over the semantic tree’s bindings, so slots come from the checker’s scopes: it, the arguments, the names parameter patterns bind, a Lambda’s captures in first-use order, the other locals by first binding site, then temps, each the lowest one released. Constants, objects and Lambda and event-test bodies are numbered as the lowering reaches them, initialiser first. Constants are shown in the display form: numbers in canonical text, Quantities with their Unit in normal form, text in NFC, map key lists, bit widths and Text Pattern canonical source, with (1), (2), … for a template’s splices. Each pass runs on an explicit task stack, so deeply nested expressions and blocks lower without the native call stack.

disassemble writes chapter 8’s canonical text, with LF line ends and a final newline: one space between fields, numbered constant, local, variable and body operands with their notes, display-form keys, every other operand by name, and the event table’s branch format. Each instruction’s position follows chapter 8’s source map, including its positions for the instructions that rules emit beyond the constructs the map lists. Those rules, the initialiser body name, the bare ... lowering and the release of repeat for each’s temp were settled in chapter 8 with this slice.

Some constructs check without error but chapter 8 doesn’t settle their lowering, so compileSource throws LoweringError at them: a bit field whose width isn’t an integer literal and a Container rooted in a well-known object. A delete of a delimited item evaluates delimited by twice, as chapter 8’s rule is written.

Terminal window
bun test impl/ts/tests/lowering.test.ts
bun run corpus:run disassembly
bun run corpus:bless disassembly/expressions

Core tests lower the Standard Library, every corpus source and the prototype’s coverage file, and check every body against machine.toml: operands, stack effects on every path, a single depth at every instruction, Unwind Table depths and bodies that can’t run off their end. They also pin slot order, temp reuse, definitions, Lambda naming, event tables, positions, constant displays, deep nesting and the unsettled cases. The non-normative prototype in tools/machine/ was used as a differential check during development: it agrees instruction for instruction on the Standard Library and the seed corpus, except where chapter 8 decides against it (source positions of stores, loop tests, Guards and try instructions; < < before a leading group; Unit plurals; canonical number text; and Rest bindings’ slot order).

import { compileSource, deliver, loadScript, text } from '@northtalk/ts';
const unit = compileSource('on greet name\n return "hi " & name\nend greet', {
name: 'greeter',
}).unit!;
const script = loadScript(unit); // runs the initialiser, uncharged
const run = deliver(script, 'greet', [text('Ann')]);
console.log(run.finish()); // { kind: "completed", result: "hi Ann" }
console.log(run.fuel, run.alloc); // Cost Model 0's Fuel and allocation

loadScript materialises a code unit’s constants, refuses a literal Text Pattern past the patternSize limit, and runs the initialiser uncharged. A failure is a LoadError. deliver starts a Run that dispatches a message to a Handler’s clauses, and callFunction runs a named function. Run.finish() gives the outcome: completed with its result, errored with its error map, limit fault with the limit, instruction and position, or unhandled. Run.records lists every raise, caught or not, with its code, instruction and position. These are Core APIs for the Group and the corpus runner that follow. The embedding interface’s Group, Load, Deliver, Pump and Trace sink come next.

The machine follows chapter 8’s state: a Run’s frames, each with its body, pc, locals and operand stack, plus iterators and replacements as internal values. Handler Clause dispatch tries clauses in order, by parameter count. A guard region’s failure reaches the clause’s clause-fail, and the next clause is tried. Calls check the call depth limit first, fill missing arguments from their defaults, and pass a Lambda’s captures in its capture slots. Errors unwind through the Unwind Table. catch pushes the error, and finally runs the cleanup copy, whose end-cleanup raises again. An error in a cleanup copy replaces the one in flight and keeps it as during. A Core-raised error is chapter 6’s map, code, message (from the catalogue’s template), its fields, then at.

Each instruction is charged its costs.toml rate before it acts, with the clause rate added at a clause body’s first instruction and unwind at the raising instruction for the frames it pops. A Built-in is charged by its own rate. A Run that can’t pay has its Limit Fault at that instruction, Fuel before allocation, and its Script Variables roll back to the Segment’s start. The syntax generator compiles the same Cost Model into browser-safe charge functions and leaf-size paths in src/generated/costs.ts, preserving each term’s ceiling and internal input/result size overrides. Composite logical sizes retain the general formula evaluator and leaves-first traversal: shared nodes are cached once while their size counts at every Script-visible occurrence. This slice settled what scanned counts for the compare, member and chunk-get rates, and that a zero has one digit, in costs.toml.

The Group runs simple instructions through Run.fastSteps once a Run’s clause is selected and no debugger is attached (#1297). It covers const, pop, load, store, move, jump, both branches, comparisons, and add, subtract and multiply of small integers. It takes precomputed charges and branches on a comparison without making a Boolean. It hands any other instruction, any charge the Run can’t pay and the Fuel Slice or cap boundary back to step, so Traces, Fuel and allocation are unchanged. A number that is a safe integer with exponent 0 keeps a JS number and makes its text and BigInt parts on first use. tests/fast-steps.test.ts compares the two paths at every Fuel and allocation limit and Fuel Slice.

The values and operations implement chapter 3 and 4’s rules for Nothing, booleans, numbers, Quantities, text, Bytes, Instants, Civil Dates, lists, maps, ranges, Text Patterns and Function Values. Arithmetic is exact BigInt decimal work: each result is rounded half-even once to 34 digits, checked for overflow and given the operator’s ideal exponent. Chunks of text, lists and integer ranges are read, written, padded and deleted as chapter 4 says, and Built-in properties, conversions to text and numbers, searches, and the value, number and text Built-ins are implemented. Text Patterns compile to chapter 8’s programs and run on its Pike VM, whose steps charge Fuel, including for text needles. Matches, the Match Search, replace, splices and Destructuring Captures follow.

the items of x delimited by d validates d before reading text, a list or an integer range, including an empty list or reversed range. An empty delimiter raises out of range with field "delimiter"; a non-text delimiter raises wrong kind with expected "text", at the property expression.

Quantities keep their Unit as one slot per Unit Kind, in Kind order (src/units.ts). Arithmetic and as with a Unit go through Base Units, multiplying and dividing by each factor in turn, every step rounded, with the result in the left operand’s Unit or the Unit as names. Equality and ordering compare values in Base Units. abs, floor, ceiling, truncate and round keep a Quantity’s Unit, and ranges may have Quantity ends of one dimension. This slice settled, as Spec fixes, that a Unit names one Unit of each Unit Kind (2 m*ft is bad unit, and 2 m*m is 2 m^2), the expected field of ^’s wrong kind, the incompatible units fields when a plain number takes part (1) or a Calendar Unit can’t stand alone, that as past the number limits raises can't convert, and the Value Encoding’s singular Units.

Unit slots and their arrays are frozen and shared by internal Quantity results. Caller-supplied slots are copied before ownership is taken. Dimensions, normal text and ordered factor sequences are cached by owned Unit identity; sequences longer than 128 factors use the general conversion path without being retained. A weak combination cache holds at most 256 results before resetting. Each loaded code unit prepares its static as and can be Unit targets once, with plans rebuilt on Reload and Restore. These caches change neither Decimal factor operations nor logical allocation, Fuel, Value Encoding or saved state.

Bytes are built field by field by bytes-field, bytes-sized and bytes-bits, and read back by the bin-… instructions over a reader, never searching or backtracking (src/binary.ts). Integer fields are two’s complement, big-endian unless little, and bit fields most significant bit first. as text decodes strict UTF-8, keeping a byte order mark, and then normalises. A Bytes search runs a literal program over the bytes, one position per byte, so it counts the steps a text literal search does. This slice settled, as Spec fixes, chapter 8’s bytes-sized for v as n bytes, which bytes-field couldn’t take a size for, the fields of each build and byte-write error, that a literal field outside a byte never matches, how Bytes searches count steps, what bin-field charges for bin-literal and bin-bits, and the canonical Base64 of $bytes. The Core’s parser also now reads a build whose first field is a build, << <<1, 2>> >>.

^ uses the correctly rounded power math for fractional number exponents, with the power operator rate and "^" in overflow errors. A negative base names "power" in its domain error. Integer exponents keep their ideal exponent, and Quantities still require a positive integer exponent.

Instants are epoch microseconds, and Civil Dates a date with an optional time of day as microseconds since midnight (src/dates.ts). The calendar is proleptic Gregorian, computed in BigInt, so a result past 9999 raises out of range with its exact year. Date arithmetic follows chapter 3’s table, with exact durations taken to whole microseconds, rounded half-even, and calendar durations as whole months, clamping the day. Date text takes a fraction of one to six digits; seven or more is refused, never truncated, and save format 8 refuses nanosecond-era saves (ADR 0091). The date Built-ins, including ISO 8601 weeks and toCivil and toInstant at a fixed offset or under Zone Rules (ADR 0179), follow chapter 7. This slice settled, as Spec fixes, the incompatible units and wrong kind fields of date arithmetic, that as civil date trims White_Space, and that a year 0000 or an Instant past the range in UTC raises out of range. It also fixed a Built-in that raises being charged a rate that doesn’t exist, rather than its own.

The number functions sqrt, exp, ln, log10, power, the trigonometric functions, degrees and radians are correctly rounded (src/math.ts). sqrt is exact from the integer square root. The others work in BigInt fixed point to a precision with a known error bound and raise it until both ends of the bound round to the same number, after first finding the values that could sit exactly on a rounding boundary: exp(0), ln(1), a power of ten’s log10, a rational power and the trigonometric zeros. The Float Built-ins read and write IEEE 754 bits exactly, with no Host float rounding (src/floats.ts). This slice settled, as Spec fixes, the value of power’s and atan2’s out of domain, which of two shortest decimals a float reads as, and the sign of a float written for a number too small.

What a later slice adds is raised as NotImplemented, never as a Script error. Outstanding work is tracked in GitHub Issues.

Terminal window
bun test impl/ts/tests/machine.test.ts

Core tests run every text-model seed case’s Script through the machine and reproduce its hand-written Script Variables and raise records, including instruction indexes and positions. They also hand-check Cost Model 0 charges, Fuel, allocation and call depth faults with rollback, unwind charges, error maps, finally and during, clause dispatch and Guards, decimal arithmetic, chunks, Lambdas, and Text Pattern matching, including chapter 8’s table of runs and their steps.

An event-loop Host can create a Group ready to run Requests:

import { createGroup } from '@northtalk/ts';
await using group = createGroup({ name: 'demo' });
const script = group.load({
name: 'main',
source: 'on go\n return 7\nend go',
});
console.log(String(await script.handlers.go())); // 7

createGroup uses the process-wide TS Core by default, or a supplied core. The /wasm export requires the Core returned by its asynchronous createCore. It forwards all newDrivenGroup options and extends the shared Group with close(reason?) and async disposal, using the driver’s shutdown behavior below.

Scripts loaded by createGroup have handlers.<name>(...args): arguments pass through toValue(arg, { numbers: 'integer' }), then invoke, and answers through default fromValue. A number answer is a Decimal, a map a plain object; Instants and other kinds without a plain JS form stay Values. Safe-integer JS numbers work as arguments; fractional or unsafe numbers reject with invalid value, naming the one-based argument position and dec() or { numbers: 'decimal' } as the fix. Script errors pass through unchanged. then, symbols, Object.prototype names and invalid message names read as undefined; a valid but undeclared name rejects as invoke does. Selectors use brackets, such as script.handlers['move:to:'](https://github.com/odogono/odgn-talk/blob/main/impl/ts/2, 3).

group.load<{ total(a: number, b: number): Promise<Decimal> }>(options) lets the Host state the type of handlers; nothing checks that declaration at runtime. By default, arguments are PlainValue | number | bigint and answers are PlainValue. With TypeScript’s noUncheckedIndexedAccess, default Handler reads need a non-null assertion, such as script.handlers.go!(). handlersOf<T>(script), exported by both entry points, provides the same calls for any shared Script, using its existing driver or Host Pump loop. script.invoke continues to take and return Values.

inlineGrants exposes plain JS functions as Operations, alongside ordinary Grants:

import { createGroup, inlineGrants, type Decimal } from '@northtalk/ts';
await using group = createGroup({ name: 'demo' });
const script = group.load({
name: 'main',
grants: inlineGrants({
math: { sum: (a: Decimal, b: Decimal) => Number(a) + Number(b) },
api: {
fetch: {
arity: 1,
async: (id: string, signal: AbortSignal) =>
fetch(`/items/${id}`, { signal }).then(response => response.text()),
},
},
}),
source: 'on go\n sum 10, 10\n return it\nend go',
});
console.log(String(await script.handlers.go!())); // 20

Each outer key defines a Capability and grants all its Operations. Spread the result beside real Grants when mixing them. Arguments have shape.value and pass through default fromValue: numbers arrive as Decimals, maps as plain objects, and kinds without a JS form stay Values. Results pass through toValue(result, { numbers: 'integer' }), so safe-integer JS numbers, bigints, plain data and Values work; a fractional JS number fails the call with invalid value, naming dec() or { numbers: 'decimal' }. A callback’s thrown ScriptError reaches the Script with its fields; other exceptions keep ordinary Host callback failure behavior.

A plain function, or { fn, arity }, is immediate. { async: fn, arity?, maxPendingMs? } suspends and receives the call’s AbortSignal after the Script arguments; abandonment aborts it. Its pending limit defaults to the Group’s maxWaitMs. Arity is always fn.length unless overridden, so supply arity when the signal parameter, default parameters or rest parameters change that count. Operations cost zero Fuel beyond call instructions, have no Argument Labels and are Host Commands: ask math to sum 10, 10 and sum 10, 10 both answer in it; write fetch id and wait for a suspending one. Existing argument-count, Reserved Word and ambiguous-command checks apply. Both TS entry points export this Helper, which works over the TS Core and Zig Host Adapter.

zoneRules(zone, from, until) builds Zone Rules from the runtime’s Intl zone data, so a Script can convert local time with toCivil and toInstant, even in a Guard, without a calendar Grant:

import { createGroup, zoneRules } from '@northtalk/ts';
const now = Date.now();
const year = 365 * 86_400_000;
const site = zoneRules('Europe/London', new Date(now - 2 * year), new Date(now + 2 * year));
// Pass `site` to the Script as an ordinary map, e.g. as a Handler argument:
// on raised at, site where hour(toCivil(at, site)) >= 22
  • A modest window: a few years either side of now. Every toCivil or toInstant call checks the whole map, at 10 Fuel plus 2 per change, so a ±10-year window in a zone with summer time costs about 90 Fuel a call. Build Zone Rules again, say once per Run, rather than reaching decades ahead.
  • No extrapolation: unlike Java’s ZoneRules, these hold only their window. A time outside it raises out of range.
  • A copy: the map holds the offsets Intl gave when it was built. Rebuild it to pick up new zone data.
  • Failures: an unknown zone, an empty window, or an offset that isn’t whole minutes, as in local mean time before a zone adopted standard time, throws invalid value.

Both TS entry points export it, and it works over the TS Core and the Zig Host Adapter.

For a Host that owns the Clock and Pump loop, use newGroup directly:

import { newGroup, parseInstant } from '@northtalk/ts';
const group = newGroup({ name: 'demo', trace: line => console.log(line) });
const counter = group.load({
name: 'counter',
source: 'script variable n = 0\non bump\n add 1 to n\nend bump',
});
counter.deliver({ name: 'bump' });
group.pump(parseInstant('2026-09-30T09:00:00Z'));
group.inspect();
// > load counter identity=…
// > deliver d1 to=counter message=bump
// > pump clock=2026-09-30T09:00:00Z
// seg counter/r1 start delivery=d1 handler=bump clause=1 fuel=17 alloc=16 state=16 end=return
// run counter/r1 outcome=completed delivery=d1 handler=bump fuel=17 alloc=16
// pumped state=idle fuel=17
// > vars
// vars counter n=1

The Group follows talk.ts for the subset implemented so far:

  • newGroup takes a name and an optional trace sink. group.load checks, lowers and loads a Script, writing load with its code identity, or diag records and a LoadError. A Script’s well-known objects are its objects; an otherwise unbound send receiver names a Script.
  • Script.deliver and Script.request are queued. Each gets its delivery id at the call. A limit override that loosens a limit, or a full mailbox, is refused there: its line is written with no id, then refused, then HostError or MailboxFull is thrown. Inside a Pump the refusal is still immediate, but its input and refused records follow the Host crossing’s call or prop record, before result conversion. A Request’s result settles with the Run’s result, or rejects with ScriptError send failed.
  • Combined worker calls: script.requestPump(message, now, options), group.requestPump(object, message, now, options) and group.callPump(fn, args, now, options) admit once and run one ordinary Pump, preserving earlier inputs. Options combine signal, fuelSlice, fuelCap and Call’s limits. A PumpedRequest with admitted: false carries error and no handle. With admitted: true, requested holds the delivery id and result Promise; pump is either {ok: true, result} or {ok: false, error}. A refused Pump leaves that Request queued and notifies readiness. A successful Pump can leave it pending. The initial admission omits readiness; callbacks can queue inputs, but worker calls refuse before admission. Ordinary Request/Call and Pump Trace records remain unchanged.
  • group.pump(now, { fuelSlice, fuelCap }) follows chapter 5. It checks the Clock, then writes the queued inputs and its pump line. It drains the queue into each Script’s mailbox, and runs turns in load order until no work is left. A Fuel Slice preempts a Script’s Run before its next instruction once the Script has spent its slice, and an overrun is carried to its next Pump as debt. Pending wait for test bodies, including failed tests, spend Pump Fuel, the receiving Script’s slice and debt, and the Group cap. Observation finishes for every pending wait before a spent slice or cap preempts the incoming Run’s first instruction. Test costs remain uncapped against the waiting Run, which faults only at its next resumed instruction. The Fuel cap ends the Pump. It returns run end, unhandled and decided reports.
  • The records: each Stretch is written as seg or preempt, after the raise, guard-skip and fault records it made, then run once the Run ends. A Core-raised error map is written without its message. Persistent State is the Script Variables and the messages in the mailbox, and a Run’s end faults on the cap there.
  • group.inspect() writes vars for each Script, in load order.
  • Capabilities: defineCapability(name, ops) takes Operations with their Shapes, cost, mode and declared errors, built with shape, and capability.grant(ops, binding) makes a Grant for load‘s grants. A Capability with a binding names its type by currying: defineCapability<Db>()(name, ops). Each Host function takes its arguments in their Shapes’ JS forms and may return its result’s: see Typed Host functions. Each ask, tell and say is checked at load against the Script’s Grants. Immediate and fire-and-forget calls run inside the Run: the arguments are checked against their Shapes uncharged, then base and declared Fuel, declared allocation and pending dispatch are charged atomically, then the Host function runs with a Call whose charge can draw more, then the result is checked and its conversion charged. A valid ScriptError it throws raises its code with its message and Data as fields. Data must be a map or Nothing; other kinds become host error with Host-only detail in a call failed report, for Operations and Object property getters and setters. Other Host exceptions also become host error with a call-failed record.
  • Interrupted Operation crossings: if Stop or a newly landed cancellation interrupts the Run at an Operation crossing, the Host failure raises no host error and emits no call failed; the call error record is still written. Operation failures during cancellation’s finally cleanup still raise and report normally.
  • Optional Capability arguments: a trailing suffix of shape.optional(...) positions may be omitted. Load checks, including Library compilation and every import, share the Run’s argument-count rule. Supplied literals and values are still checked, and the Host receives only those arguments, with explicit Nothing preserved. The Trace, pending-call inspection and Reissue keep that same list. say still takes exactly one source argument. This supplies the arity support Calendar and Locale factories need.
  • Standard Capabilities: clockCapability(costs) reads the Pump’s Clock with no Host implementation. timerCapability(impl, costs) checks its fixed argument Shapes and forwards schedule and cancel to the Host with the Script name and Grant binding. The Host stores timers durably, replaces names within each Script, and delivers due messages; the Core stores none. consoleCapability(impl, costs) forwards every Value to write for display in text form, and starts read with a Call the Host answers with text. Its fixed human-input timeout, cancellation signal and declarations survive the same save/restore paths as ordinary Capabilities. shape.value accepts Function Values at any depth, while shape.any keeps its data-only check. Costs are copied and validated at factory creation. The Trace runner supports these through [[standard]], including calls in Libraries and save/restore replay. calendarCapability(impl, costs) supplies all six immediate Calendar Operations, passes the Grant binding and optional zone to the Host, resolves toInstant disambiguation, checks date/time result refinements and permits only declared Calendar catalogue failures with valid fields. The Host owns zone data. The Spec now settles Nothing defaults, three-argument disambiguation and uncharged domain checks. localeCapability(impl, costs) supplies all eight Locale Operations, validates RFC 5646 tag syntax without platform Locale data, fills option defaults for the Host, and checks dense ranks, comparison results, names, symbols and returned tags. The Host owns Locale data and fallback. The Spec settles Nothing/options defaults, error ordering and the syntax-only tag contract. storeCapability(impl, costs) declares the eight immediate store Operations, with set, delete, increment and swap Segment-bound. The implementation is the Segment Coordinator of every binding, so writes to several of its Stores, or to one Store through several Grants, enroll in one participant, whose begin, commit and rollback are the implementation’s (ADR 0069). The Core raises invalid key for an empty key before charging. watch name, prefix [, message] and unwatch name return Nothing, are final at the call and never enroll a participant. A missing or Nothing message means storeChanged; supplied arguments remain unchanged in the Trace. After Shapes, empty names and non-plain messages raise uncharged invalid watch with field: name or message. The factory requires the eight methods, all three Segment hooks, release and all eight costs, and forwards release for owner cleanup. The Core checks result kinds, and permits only each Operation’s declared Store failures with valid fields. add(a, b) applies the + rules outside a Run and throws the ScriptError + would raise. All six Standard Capability factories are implemented.
  • Stores: @northtalk/ts/store holds the Store implementations, none of them the Core. Stores is an engine over a StoreBackend: it keeps each Store’s committed contents in memory, every live Segment’s pending writes to each Store it writes, the key reservations of ADR 0062 and the quota checks, which count each Segment’s net growth in each Store. The backend loads a Store once and applies each commit, to every Store the Segment wrote, at once. A backend that throws makes the commit failed and leaves the engine’s copy unchanged; one that throws StoreStateUnknownError makes it unknown, and the engine reads those Stores again. memoryStores keeps nothing outside the process, and webStorageStores keeps each Store as one Web Storage item, in the format :store save writes, for browser Hosts that run the Core on the main thread. A commit to several Stores that can’t set every item puts back the ones it set. Two tabs sharing one Store are unsupported. Reservations end only at a Segment’s commit or rollback, so a Host stops and pumps its Scripts before discarding a Group that shares a Store. A sqlite database keeps the SQLite Store (below), which the store-sqlite example uses. Every Store runs the store test kit through tools/store-kit.ts.
  • sqlite: sqliteCapability(impl, costs, perStep) is chapter 9’s factory. It declares query metering: 'read-only' and change metering: 'segment-bound', and passes query and change a beforeStep callback that charges perStep; an implementation calls it once immediately before every SQLite step, the completion check and the probe past max included, and lets its LimitReached propagate without stepping. @northtalk/ts/sqlite holds an implementation on node:sqlite, so a Host on Node 24.10 or later or Bun can offer sqlite. It isn’t the Core. openSqliteDatabase(path, { stores }) opens one database file, and sqliteDatabases({ name: db }) is the SqliteImpl over the Host’s databases, by the name a binding gives. Each database is one Segment Coordinator. A Segment’s first change or begin takes the one writer connection and opens its transaction with BEGIN IMMEDIATE, and a Script transaction is a savepoint inside it. Every other read goes through a read-only connection, which sees the last committed state in WAL mode. Reservations and the write lock live in the process, so the process owns the file: it holds an exclusive lock on a sidecar database, <path>-lock, until close, and a second open fails. An in-memory database ('' or ':memory:') is refused: the reader relies on WAL, which an in-memory database can’t use, to see only committed rows while a Segment writes. Tests and demos open a file in a temporary directory instead, as Using SQLite shows. db.exec runs SQL outside every Segment, as for a migration.
    • Stores in the database: with stores quotas, db.stores is a StoreImpl on the database’s coordinator, which keeps each Store in the table store. A Segment’s Store changes and database changes commit in one transaction, and no sqlite Grant may use that table. Once sqliteDatabases offers the database, a Store write takes the write lock at its call and fails with store busy while another Segment holds it (ADR 0070). A database that isn’t offered through sqlite keeps the ordinary Store reservations, and takes the lock only for each commit.
    • Limits: node:sqlite has no sqlite3_stmt_readonly and doesn’t report where a statement ends, so the implementation scans the SQL itself for trailing statements and placeholders, and query refuses, as not read-only, any statement the authorizer sees write. node:sqlite decodes TEXT that isn’t UTF-8 with replacement characters, so any U+FFFD in a TEXT result fails with unrepresentable, including one the database really holds.
    • Guide: Using SQLite covers Script examples, Host setup, transaction behavior and the implementation.
    • Tests: tools/sqlite-kit.ts runs the sqlite test kit through the factory. tests/sqlite-kit.test.ts runs it under Bun, and tests/sqlite-runtimes.test.ts under Node.
  • Driven Groups: @northtalk/ts/driver exports newDrivenGroup(core, { name, seed?, trace?, ...driverOptions }), returning { group, drive } with readiness already wired. Use it for event-loop Hosts: Requests can be queued and awaited immediately. The factory owns onReady. autoDrive(group, options) remains available for Hosts that wire an existing Group’s onReady to drive.ready(). Both helpers use the embedding interface, so they take either Core’s Group (ADR 0121), and are outside parity. ready schedules one Pump on a later macrotask. A sliced or rewound Pump schedules another, so a Fuel Slice yields the event loop. A Pump’s nextDeadline arms one timer, which any later Pump replaces. Readings come from clock, epoch microseconds from Date.now() by default, and never go backwards. A Host with its own clock also supplies setDeadline. pump options apply to every Pump. onPump receives each result and may make worker calls; onError receives a Pump that threw, and the driver keeps going. idle() resolves once no Pump is scheduled; a Group waiting only on a deadline counts as settled. stop() cancels both scheduled Pumps and the timer; it does not stop Scripts or settle pending Requests. await drive.close(reason) stops all loaded Scripts, drains, waits for outstanding run Promises (including abandoned calls), drains their late results and then cancels scheduling. The default reason is Host shutdown; repeated closes share one Promise and the first reason. Closing works after stop() and cannot be interrupted by it. Promise rejections from Operations do not fail close; Clock, Pump or driver callback errors do. A Host Promise that never settles keeps close pending unless closeTimeoutMs is set; when it expires, close passes the pending calls to onCloseTimeout and resolves. Callback-style start calls receive abort but expose no completion Promise. Stop accepting work before closing, and release Host resources after it completes. The driver also implements [Symbol.asyncDispose]() as close() for await using Hosts. See the shutdown guide. A Host using newGroup directly must pump queued work for Requests to finish. The webhook rules Example Host uses newDrivenGroup.
  • Script counters: script.counters() returns a fresh snapshot of lifetime Fuel, allocation, Run starts and Limit Faults, plus current Persistent State and mailbox length. Live Runs, parked dispatch, event tests, Reissue and cancellation cleanup contribute exactly once; rollback and discarded work do not erase costs. Worker reads reject reentry and do not drain inputs. Reload, Extend, Library replacement and both restore policies preserve lifetime totals. The Trace runner replays counters inputs and pins all six fields. Chapter 9 now settles the counting rules, including free initialisers and Cleanup Budget failures remaining cancellations.
  • Forbidding suspension: forbidSuspension at Load runs the Suspension Point analysis in suspension.ts with every body restricted, as a finally block is, so each Suspension Point and each call to a Handler that may suspend, imported ones included, is can't suspend here. The Script keeps the option in its state: Reload, Extend and Library replacement check new code under it, the Fingerprint and the Inspection name it only when set, and a save lists such Scripts in the optional suspension section (tag 15), which restore reads back. The Zig-backed adapter passes it to the reactor, which applies the same rules.
  • Kept Grants and revocation: grantsAsUsed trims each Load’s copied Grant sets to direct uses and imported Library needs, including unused definitions and Lambda bodies. script.grants() returns an independent snapshot with sorted Operation lists, including revoked Grants. script.revoke(name) queues a Trace input for the next Pump; later calls raise capability revoked, while pending calls remain live. Reload and Library replacement check without revoked Grants and remove them only on success; Extend checks new code against unrevoked Grants. Discarded Operations cannot be regained by code changes. Save and Restore keep the Operation sets and revocation state; wider rebound templates are restricted to the saved sets.
  • Suspension: wait d, ask … and wait, send … and wait, and a Handler or local Function Value called with and wait, suspend the Run at the instruction, a Segment’s end, where Persistent State counts its frames. The Group holds its timers and pending calls: a Pump drains answer and fail inputs, which settle their calls, then fires due timers in deadline order, then runs turns, so a ready Run resumes in its Script’s queue order. A resume starts a new Segment, charges an answer’s conversion and late cost, and pushes it, or raises a failure, send failed or timeout. A timed-out call is abandoned, and a later answer is noted late-answer. The loader infers which Handlers may suspend, imported ones too, and reports missing and wait, needless and wait and can't suspend here. A Join starts its members where they stand, checking MaxJoin before each, and suspends once at its closing end; the Group waits for every member, or fails fast with the first failure and index, abandoning the rest, as an error leaving the Join’s body or a fault does. A wait for waits on its when branches, timeout and after branches; each message dispatched to its Script first tries the Script’s pending waits, in the order they began, running each event test as its own Run charged to the waiting one, and then goes to the Handler Clauses. The control checker reports not in a join and empty join.
  • Event observation: Event tests pay their own instructions, without the additional Handler Clause dispatch charge. Their Fuel and allocation belong to the waiting Run and the observing Pump; Guard errors are recorded before incoming Handler dispatch.
  • Host Objects: defineObjectKind defines a kind with its properties, and group.object(kind, id, native) makes a handle, whose parent, disposal and Owning Script the Group holds. group.object(kind, id, native, { parent }) gives the new object its parent at once, even inside a Pump, so a Script that gets it from a Host function and sends to it in the same Run reaches the parent’s Owning Script; a disposed parent is invalid value, and the Trace records it as object (ADR 0152). setParent and dispose are queued Host Inputs. setParent refuses known cycles (parent cycle) and disposed children (invalid value) at the call, then rechecks both at drain and reports any new refusal through Pump. load takes an owner and well-known objects. group.deliver and group.request route to the object’s nearest Owning Script when the input is drained; a Run that ends unhandled or with pass climbs on from the parent of the object whose owner received it, and a message past the last one is unhandled, with its target. me and the target are the objects, a send may name an object, and a Command Call with no Handler climbs from the Script’s owner. Properties are read and written through the Object Kind, as prop records, and id and isDisposed are the Core’s. If Stop or a newly landed cancellation interrupts the Run at a property crossing, the property failure raises no host error and emits no call failed; the prop error record is still written. Property failures during cancellation’s finally cleanup still raise and report normally. Before dispatch, a queued object message reads its current path and moves to the new receiver’s mailbox tail, without starting a Run or spending Fuel in the old Script. Climbed messages resume from the last owner’s current parent; Targets and reply ids stay fixed. Transfers preserve admission, and Host overrides can only cap each receiver’s limits. Object filters in wait for … from retain their evaluated Target identity through save/restore and count toward Persistent State. Disposing an Owning Script’s object stops it within that Host Input.

Wait deadlines retain their mathematical microsecond counts even outside the Clock’s years 0001–9999. Valid waits suspend and charge normally. Inspect and the Trace omit unrepresentable until values; an unreachable future deadline has no nextDeadline, and one before the Clock range requests another Pump at the current reading. Earlier Timeout Blocks, exact timer order and save/restore preserve the count (#1262).

  • Decisions: script.decide, group.decide and group.decideBroadcast return an id and a decided Promise. A deciding Run seals its Verdict at its first Segment end, including a suspension, but keeps it open across preemption; veto runs finally and completes with Nothing, and pass carries an open Verdict up the Message Path. A non-deciding clause allows at successful dispatch, a matching wait for allows immediately, and the end of the path allows with unhandled. Errors and faults before the seal are undecided. A Broadcast takes recipients at drain in load order, includes pending waits, never climbs, and aggregates every veto and undecided recipient in that order. Its limit override is an additional cap on each recipient’s own limits. decided is reported once, independently of the Run’s later end. The loader rejects veto outside an entry deciding Handler, including local Handler calls, veto in a Join, and veto or deciding pass reachable after a possible Suspension Point. This slice settled those last two language gaps and the Broadcast override rule in the Spec. AbortSignals cancel an open Decision, and a dropping clause leaves it undecided. Cancelling after the seal leaves the follow-up Run alone.
  • Broadcast: group.broadcast returns a broadcast id and takes recipients at drain, after earlier inputs have applied: live Scripts with a Handler or pending wait for. Each recipient has its own Delivery id under that broadcast id. Broadcasts never climb or report unhandled, and their overrides only tighten each recipient’s limits.
  • Cancellation and Stop: Requests and Decisions accept {signal}; the runner replays cancel-delivery only through a Request, Decision or Host Function Value call AbortSignal. It rejects a plain Delivery or unknown id, which has no public cancellation handle. script.cancelRun rolls back a preempted or active Segment, abandons pending calls and schedules dispatch-local and retained finally scopes once, innermost first; dispatch activations inherit their owners’ enclosing scope identities. Suspended, ready and parked Runs preserve committed state. Cleanup spends a separate Cleanup Budget, participates in slicing and cap preemption, and ends cancelled even when cleanup fails, with cleanupFailed in its report. An error keeps cleanup writes; a limit rolls them back. Cancelling a sender leaves its receiver alone. script.stop and owner disposal discard work without cleanup, fail senders as stopped, and settle open Decisions as undecided, cancelled. Stop is sticky. Stop and CancelRun made inside a Host function land immediately after that crossing’s record and before result conversion. script.rewindRun lands the same way: a Run still in its first Segment rolls back, is discarded with reason rewind, and its message goes back to the head of the mailbox; the Pump returns rewound. A parked Run, including one unparked but not yet resumed, preserves Script Variables committed by other Runs. script.reload(source, carry, { keepMailbox: true }) keeps that mailbox (ADR 0068). Its kept messages count toward the Persistent State cap with the new Script Variables, and RestoreOptions.keepMailbox keeps each changed Script’s mailbox in a Partial Restore the same way (ADR 0143).
  • Queueing Policies: dispatch selects a clause first. queued parks new Runs FIFO, counts their retained frames toward Persistent State and releases the first when the clause’s active Run ends. dropping ends the new Run at dispatch; replacing schedules every earlier eligible Run’s cancellation cleanup in its own turn. Called Handlers don’t apply entry Queueing Policies. Inspect lists every Run in start order, including parked Runs. Ready Runs, their retained answers and cancellation cleanup also count toward Persistent State.
  • Reload, Extend and Library replacement: script.reload(source, carry) stages checking and initialisation before discarding old work without cleanup. It resets variables or carries them by name, drops all extensions, makes old Function Values stale, and preserves the Script’s Host bindings, limits, counters and load order. script.extend(source) adds only new names in a separate code unit, links existing definitions and variable slots, and keeps old Runs and Function Values live. An extension that would exceed Persistent State is refused unchanged, as now settled in chapter 10. group.replaceLibrary(library, carry) checks and rebuilds transitive Library importers and every affected Script with its extensions before changing anything; successful replacement stops affected Scripts in load order. The runner replays all three inputs. Their Trace source fields use display-form text while preserving the exact source scalars, including decomposed text, as now settled in chapter 11.
  • Function Value calls: group.call(fn, args, {signal, limits}) queues a Host Request to the Home Script. A foreign f(x) and wait pays the call rate and starts a concurrent mailbox Run there, with that Script’s Grants and limits. Defaults and captures bind in the value’s code unit. Replies, errors, cancellation, timeouts, Stop and pending foreign calls after restore reuse the message machinery. Group identities reject foreign and old Host handles at every inbound Host boundary, including nested values and captures; stale Host calls fail at drain. Foreign waits use the effective Run MaxWait override. Library Constant callbacks, including nested values and defaults, bind to each importing/calling Script. readDisplay takes an optional third argument resolving a Function Value’s complete display form against a previously held handle; corpus replay remembers nested handles from reports and Capability arguments. The Spec settles arity checks outside a Host-called function’s body, no-clause charging, mailbox contents, inspection labels and {fn, args} in an uncaught error’s during binding.
  • Run accounting: Pump, Reload, Library replacement and Restore return dispatch/discard lifecycle events and cumulative per-Run Fuel and causal queue counts. Detached sends and error Handlers retain ancestry; observation charges stay with the waiting Run. Accounting adds no Trace records or execution costs.
  • Save and restore: group.save() emits bytes in the save format every Core shares (ADR 0144; it writes format 2 and still reads format 1; older formats are rejected, with no migration), so a save restores on the TS Core or the Zig Core whichever took it, without native objects, Host callbacks, bindings or futures. restore(bytes, {libraries, grants, resolve, onMismatch, name, trace}) stages code and compatibility checks before resolving objects, then rebuilds shared machine state, including preempted frames, dispatch contexts and activations, shared owner locals, pending transfers and arguments, cleanup progress and attempt counters, rollback bases, counters, debt, queues, timers, Joins, open Decisions, extension closures and Text Patterns. Before rebinding a Run, Restore validates code/body/PC identities, owner-local aliasing, dispatch phases, action arity and slots, cleanup table references and acyclic ownership; malformed control returns invalid save. A mismatch rejects or carries variables by name, discarding work and reporting open Decisions at the first Pump. group.settle(id, settlement) accepts Answer, Fail, Reissue or Adopt once before that Pump; missing settlements fail as call lost before timers. Reissue charges count toward Pump cap and slice debt. Adoptability follows the original call style, and queued settlements survive another save. group.objectById(kind, id) returns the handle with that kind and id, disposed or not, which is how a Host reaches the handles Restore made. group.fingerprint() hashes canonical code, Library, Grant declaration and limit data, excluding runtime state and Host implementations. group.stateFingerprint() and core.stateFingerprint(bytes) give 32 bytes that match exactly when two Groups’ saved state matches apart from the Trace save id counter, so two saves with nothing run between them, a save and its restore, and Embedded- and External-source saves of one state all agree; the live form refuses as save() would, writes no Trace record, and the save form throws invalid save or save mismatch. To see where two saves differ, run northtalk diff-save a.save b.save, or call diffSaves from @northtalk/tooling/save-diff in a test (CLI). The Spec now fixes inner declaration key order, optional error catalogue semantics, Save counter effects, numeric call ordering and partial Broadcast discard aggregation.
  • Uncaught errors: a Run ending errored queues an ordinary error message for its Script’s on error clauses. Their text shorthand matches code, and during binds {name, args} for a message or {fn, args} for a Function Value call before dispatch tests. Function metadata retains the original Function Value and captures through local calls, preemption and Save/Restore. Pending wait for error subscriptions observe it even without an on error clause. The queued message counts toward Persistent State until dispatch. An unmatched internal error message never climbs, a full mailbox notes error-dropped, and an error Handler that errors sends no further error message.
  • send puts a message in another Script’s mailbox, written as a send record, and its Run starts from the sending Run. A receiver Name that resolves to nothing else names a Script, even one loaded later, and a Script the Group doesn’t hold raises object gone. me names the Script’s owner, or sends to the Script itself when it has none.
  • compileLibrary({ name, version, source }, imports, declarations) checks and compiles a Library once per process for each code identity, running its initialiser to compute its Constants, or throws LoadError. Its optional declarations argument is a GrantDecls map of modes, argument Shapes and command flags. Its optional fourth argument, { atCaller: true }, is TS-only and outside the Spec: an error raised in the Library gets an at naming the call that entered it, as for stdlib code, while the Trace still records the raise by its Library instruction. northtalk test compiles its Test Library this way. Direct calls are checked on every request, including cache hits; needs is a sorted, deduplicated list that includes every definition and transitive import. Script imports check all needed Operations and revalidate their call modes, counts and literal Shapes against the caller’s kept Grants. Missing Operations report missing grant at the Script’s use line with the Library call site in the diagnostic message. Reload, Extend, replacement and restore use the same import checks, and replacement retains dependent Libraries’ compile declarations. The runner supplies declarations from case.toml. group.addLibrary writes add-library with its identity, and refuses a stdlib name, a name the Group holds, or a Library whose imports the Group doesn’t hold with the same identities. A Script’s and a Library’s code identity covers its direct imports’.
  • Library calls run in the caller’s Run and cost what a local call does. Each frame runs in its own code unit, a Script’s or a Library’s, so its constants, defaults, Constants, Unwind Table and positions are that unit’s, and an error raised in a Library names it in at. An imported Constant is the Library’s value, linked at load. A Function Value made from Library code has the calling Script as its Home Script, and is placed by its Library, as in <function shelf:deco:10:10>. The seven stdlib Libraries are always there, with no addLibrary: the Core carries their normative source from spec/stdlib/ (src/generated/stdlib.ts) and compiles each on first use, with the language version as its version. An error raised in stdlib code, by its throw or by an operator or Built-in there, gets an at naming the call that entered the stdlib, in the nearest frame that isn’t stdlib code. A catalogue error the stdlib throws without a message is Core-raised, so it gets its template message and the Trace leaves that out (ADR 0037).
  • Restricted callbacks: the trusted stdlib loader alone lowers private map:restrictedCall to call-restricted. The inherited frame restriction rejects live Script state, Host effects and recovery-context access before acting, and survives catch/finally, preemption and restore. Host compilation, including { atCaller: true }, cannot enable it. Snapshot format 8 rejects earlier formats. The map.transform Library export uses this boundary for callbacks; no public pure-call API is available. See the normative contract and the cross-Core kit.
  • Mappings: map.transform implements ordered, presence-aware Mappings from the shared normative Library source, including wildcard/default/skip selection, complete Shape checks, definition validation before callbacks and complete output or ordered diagnostics. Limit Faults escape. The contract fixes definition precedence and concrete source locations; mappings.test.ts and the stdlib/mappings* Corpus cases cover behavior, sliced restore and resource exhaustion.

Instants are epoch microseconds, written in the display form. Code identities use a bundled synchronous SHA-256, so the Group stays browser-safe.

The Host-side decodeJson and encodeJson follow chapter 7’s plain JSON mapping, with a shared test table against the json Library. Numbers are read from their digits, keeping scale and applying JSON exponents exactly. Invalid JSON throws ScriptError with can't decode and {format, offset}; unsupported value kinds throw not encodable with {kind, path}. The exported coreVersions (Versions) reads the generated language, Cost Model and Unicode pins, and the save-format constant shared by save and restore; core is the informational TS implementation version.

corpus:run replays a Trace Case’s Host Input lines through the Group and compares the Trace it writes, ignoring comments and blank lines. It also compares a replay with save/restore between eligible Pumps, adopting pending Calls; boundaries that require old Host handles are skipped as chapter 11 specifies. A Host Input line may leave out its filled keys and the ids the Core assigns. A case that needs a Host Input or a feature this Core doesn’t implement yet is reported as deferred. The default selection runs every case; a case awaiting first review still says # Unblessed: in its header. A failure ends with a reproduce: command. --bless writes a named case’s expected output from the TS Core alone, preserving Trace comments and blank lines; bun run corpus:bless uses it and keeps the result only when the Go Core agrees. See the corpus guide for selection, cross-Core agreement and first-blessing review rules; support and reviewed expectations are separate concerns.

Terminal window
bun test impl/ts/tests/group.test.ts tests/corpus.test.ts
bun run corpus:run text-model/host-text-joins-in-nfc

The native TS Core supports group.save({sources: 'embedded' | 'external'}). Omitting the option keeps an Embedded-source Snapshot, including each Script’s base and extension sources. Both modes use the same compact, checksummed JSON graph and deduplicated Grant declarations. Libraries, bindings and native objects still come from the Host. Compression belongs to the Host.

An External-source Snapshot keeps ordered code-unit identities instead of Script sources. Restore requests each bundle synchronously:

const bytes = group.save({ sources: 'external' });
const restored = core.restore(bytes, {
name: 'game',
libraries,
grants,
resolve,
onMismatch: 'reject',
scriptSources: ({ name, identities }) => codeCatalog.lookup(name, identities),
});

scriptSources returns {source: string, extensions?: readonly string[]}; extensions apply in that order. Keep exact source text and Library identities for full continuation: even comments and whitespace contribute to code identity. A missing bundle fails with save mismatch, even under onMismatch: 'variables only'. The callback is never used for embedded sources.

A Host may deliberately return current code when historical sources are gone. Only variables-only policy accepts a different identity: the whole Group loses its continuations, mailboxes and input queue, even for unchanged Scripts. Variables carry by name from prospective post-rollback bindings; counters and accounting remain, Function Values become stale, and Restore reports discarded Runs/messages/calls. A missing Script needs an explicit replacement bundle. Load failures and Persistent State overflow fail the restore as a whole. A Host can then use its ordinary Reload policy. For pending calls after a full restore, settle each before the first Pump as usual.

router.save(group, options) forwards the source mode when checkpointing Store watches; router.restore forwards scriptSources through its restore options. Session saves retain embedded sources. The option is native TS only: Go, Zig, the Message Layer and @northtalk/ts/wasm do not support it. There is no cross-Core compatibility or legacy format reader. Format-9 saves must be consumed with the old Core or replaced under the Host’s own upgrade policy.

See chapter 10 for the contract and the snapshot benchmark for reproducible synthetic size and timing measurements.

Terminal window
bun install --frozen-lockfile
bun run unicode:generate
bun run unicode:check

The generator downloads all ten files pinned by unicode.toml into .cache/unicode/18.0.0/ when absent. Every invocation checks every file’s SHA-256; corrupt cached data fails rather than being silently replaced. Delete the offending cache file to download it again. unicode:check also reproduces the generated tables byte for byte and fails if the committed TS is stale. A fresh build therefore needs network access once, and subsequent builds can use the verified cache offline.

The committed src/generated/unicode.ts includes the source hashes. Runtime code imports only TS tables and uses no platform normalization, Intl.Segmenter, Unicode regular-expression properties or platform case mapping. Hangul normalization is algorithmic. Extended grapheme boundaries follow Unicode 18’s UAX #29 revision 49, including its changed GB9c rule. The Unicode license accompanies the tables and is copied into dist/ with the browser bundle.

The event-test charging reconciliation records the paired executions and the limited approval for TS-only expectation corrections. Current Go facilities are described in the Go save/restore guide; implementing those facilities and verifying each corrected Trace are separate steps.

At a waiting Script send’s suspension boundary, Persistent State includes its new 48-byte pending reply. If retaining it faults, the accepted receiver message still runs and its reply is abandoned. The paired send-wait-retention regression pins this boundary alongside ordinary Go and TS save/restore execution. Script-only Joins also count their pending members at the closing suspension boundary and retain replies arriving while an open body is preempted. Buffered replies are applied in arrival order at join-end; their answers and receiver error maps count toward Persistent State. Ordinary Capability calls and mixed Joins now agree with Go on the reviewed answer and Join cases and the new suspension/capability-resumption regression. The new case also agrees on TS save/restore. Its first blessing was approved on 2026-10-05, with a later correction approved on 2026-10-07; see the step-3 approval record. Suspending Operations and foreign Function Value calls also count their new 48-byte pending calls at the charged boundary, after consuming their operands. Event waits count each branch’s evaluated object filter and captured Values at that boundary, including repeated captures; a named Script adds no Value size. A retention fault rolls back Script Variables and abandons pending calls after the fault record, while preserving already-started Host work and receiver messages. The suspension retention audit records the tight-limit regressions, their Go/TS ordinary and save/restore agreement, and the expectations for #281, whose first blessings were approved on 2026-10-07 (approval record). Join failures, timeouts and faults at join-end use the closing end token’s source position, for bare end and end wait, including Joins in local Handlers and block Lambdas. Member indices remain 1-based, and failed replies retain the receiver’s own Error map and source position.

Terminal window
bun run lint
bun run format:check
bun run typecheck
bun run test
bun run corpus:run
bun run corpus:run --list
bun run corpus:run text-model/host-text-normalised-to-nfc
bun run build

bun run lint:fix applies ESLint fixes using @nkzw/eslint-config; bun run format formats the TypeScript sources and ESLint configuration with Prettier. CI requires both lint and formatting checks to pass. Generated Core/tooling tables and normative files under spec/ are excluded: their regeneration and Spec checks verify them instead. bun run lints:check verifies the tooling catalogue and its copies of the grammar tags and Built-in properties.

Record notable implementation changes through changelog fragments, following the commit conventions. Implementation releases are separate from Language and Cost Model versions.

Tests cover every row and all five NFC columns of the pinned NormalizationTest, identity normalization for every unlisted scalar, every GraphemeBreakTest row, every C/S folding mapping, UnicodeData and unconditional SpecialCasing mappings, final-sigma contexts, text searches/chunks, constructor refusal paths, immutable containers, insertion order, display/encoding round trips and deep values without a reader-only nesting limit.

The execution runner is separate from corpus:check, the format checker. Its default selection is the complete Corpus. Paths are relative to corpus/, or absolute; naming a case selects it even before its first blessing. --list marks each case supported or deferred. Explicitly selecting a deferred case kind fails. A mismatch identifies the case and the differing output. --bless requires named cases and writes their expected disassembly, Trace or Transcript output from the TS Core alone; it refuses encoding cases. bun run corpus:bless keeps that output only when the Go Core agrees. See the corpus guide for blessing rules.

bun run build verifies the pins and builds the publishable @northtalk/ts package in impl/ts/dist/, the browser-safe Lint bundle tooling/stack/dist/lint.js, and the Node CLI bundle tooling/cli/dist/main.js. The package build, bun run --cwd impl/ts build, bundles each published subpath with tsdown into ESM and declarations, and writes dist/package.json from tools/package/: the workspace’s own manifest stays private and exports source, and ./replay isn’t published. Its version is the one coreVersions.core reports. bun run --cwd impl/ts package:check packs dist/, installs the tarball outside the workspace with npm engine enforcement and runs it under Node and Bun (including a real SQLite Capability query); CI pins Node 24.10.0. It also loads the package unbundled in Chromium through an import map and checks its declarations against TypeScript 5.9 and the latest TypeScript; it needs Playwright’s chromium-headless-shell. To check it in a real browser, run bun run --cwd impl/ts test:browser and visit http://127.0.0.1:3926/. The smoke test disables platform Unicode functions and checks values, encodings, display forms, deeply nested values, lossless parsing, syntax and load diagnostics, and lowering and disassembly. Stop the server when finished. CI checks lint, formatting, regeneration, types, tests, the implemented corpus selection, the browser build and all existing spec/grammar/lowering/corpus-format checks.

GitHub Issues track outstanding work and acceptance criteria. Appendix B explains the implementation order. The corpus guide describes coverage and blessing; passing the available corpus does not establish complete conformance.

A NotImplementedError fallback by itself does not establish missing language behavior: unsupported constant, Library and kind branches can also guard unreachable or invalid inputs.