9. Embedding
Draws on: ADR 0001, ADR 0002, ADR 0004, ADR 0005, ADR 0006, ADR 0008, ADR 0009, ADR 0011, ADR 0012, ADR 0014, ADR 0015, ADR 0016, ADR 0017, ADR 0020, ADR 0025, ADR 0026, ADR 0028, ADR 0030, ADR 0031, ADR 0038, ADR 0039, ADR 0063, ADR 0077, ADR 0102, ADR 0152, ADR 0179.
A Host embeds a Core through one interface, declared in talk.go and talk.ts. The two files have the same calls, and differ only in idiom: errors as values in Go and exceptions in TS, Start and Answer in Go and an optional Promise-returning run in TS, and maps built from pairs in Go and from a Map or record() in TS. No Script can observe the differences (ADR 0015). They are declarations only, and are never compiled. This chapter states the rules they share, and the language-neutral message layer for a Host in any other language.
The checked interface files carry the Metered Operation declarations, including the SQLite perStep signatures; legacy interface comments do not override that contract.
Package names
Section titled “Package names”The Go embedding’s module path is northtalk.org/go, with the public package named northtalk at the module root (ADR 0046). The TS Core’s package is @northtalk/ts (ADR 0102).
The shape
Section titled “The shape”Coreis process-wide. It holds the compile cache, so a Script or Library with the same code identity compiles once. It defines Capabilities and Object Kinds, compiles Libraries, and makes and restores Groups.- TS helpers:
createCore()returns the process-wide Core. The package also keeps its free-function helpers (defineCapability,compileLibrary,newGroup,restoreand the Capability factories); they use the same process-wide definitions and compile caches. Creating a Core does not reset those definitions or caches. Each Group still owns its live state.
- TS helpers:
- Making a Group:
NewGrouptakes the Group’s name and, optionally, the seed of the generatorrandomdraws from, a whole number from 0 to 2^64 − 1. Without one the seed is 0. A restored Group keeps its saved generator state instead. Grouptakes every Host Input: load, add and replace Library, deliver, request, broadcast, decide, call a Function Value,setParent, dispose, pump, save and settle. It also gives the Group Fingerprint and an Inspection. Host Objects are made per Group, since parents and disposal belong to it.Scriptis a handle for calls addressed to one Script: reload, extend, stop, cancel or rewind a Run, revoke a Grant, counters, and deliver, request or decide to the Script itself.
Threads and the input queue
Section titled “Threads and the input queue”- Queued calls:
Deliver,Request,Broadcast,Decide,DecideBroadcast,Call,SetParent,Dispose,Stop,CancelRun,RewindRun,Revoke,Answer,Fail,RequestChargeandSettle, and cancelling aRequest,DecideorCallthrough its context or signal. They are safe from any goroutine. Each appends to the Group’s input queue, callsOnReadyand returns at once, with a delivery id where it has one. - Host Objects:
ObjectandObjectByIDare safe from any goroutine and from inside a Pump, such as from a propertyGet. They don’t queue: a handle is made, or found, at the call. - Script names:
ScriptNamesis safe from any goroutine and from inside a Pump. It gives the Group’s Scripts’ names in load order, so a Host helper that orders work by Script, such as a notification router, can read it while a Pump runs. It reads the Group without changing it, isn’t a Host Input and adds no Trace line. - Libraries:
Librariesis safe in the same way, and charges nothing. It gives the compiled user Libraries the Group holds now, in the order the Group added them, in the formRestoreOptions.Librariestakes. AfterReplaceLibrarythat includes every Library the Core recompiled because it imports the replaced one, whose identity has changed. It gives no stdlib Library, since the Core supplies those itself. - Draining: the next Pump takes its Clock reading, then drains the queue in call order and records each input in the Trace there. A Pump never sees an input arrive halfway through.
- Stop, cancel and rewind:
Stop,CancelRunandRewindRunland at the latest at the running Pump’s next Host crossing (an Operation or property call) or at its end. A native Core may act on them sooner, between instructions. Asetthrough a property’s value is one crossing: no Stop, cancel or rewind lands between its walk, itsGetand itsSet. One made then lands after theSet’sproprecord, or where thesetraises (chapter 4). Scripts and replay parity can’t tell the difference, since the Trace records where each one landed. Everything else waits for the next Pump. - Rewinding a Run:
RewindRunends a Run that hasn’t passed a Suspension Point as if it had never started (ADR 0068). Where it lands, its Segment rolls back as at a Limit Fault: Script Variables, unless the Run is parked or has been unparked but has not resumed its clause body, and the Segment-bound participant. Such a Run has no variable changes to undo; changes committed by other Runs since its dispatch stay committed. Its live scopes and pending calls are abandoned, and it ends with nocatchorfinally. Its message goes back to the head of its Script’s mailbox, with its delivery and reply ids and its place on its Message Path, so a waiting asker keeps waiting and an open Decision stays open. Effects already made, other than the participant’s, are final. The Pump it lands in returns at once, in staterewound, so the Host can Reload before the message is dispatched again; its Fuel is not refunded, and dispatch is charged again. One that lands on a Run that has passed a Suspension Point, or has ended, does nothing, and the Trace notes it asnot-rewindable. - Cancelling a Request: cancelling its context or signal queues
cancel-delivery. It cancels the Run the Delivery started. A Delivery still in the mailbox is removed instead, and reported as arun endwith outcomecancelledand no run or Handler. PlainDeliverhas no cancellation context or signal; its delivery id alone cannot be used to queuecancel-delivery. - Durations:
MaxPendingandMaxWaitare whole milliseconds. Go refuses a finertime.Duration, and TS a fraction, asinvalid value. - Synchronous errors: a queued call returns an error only for facts known at the call, such as a full mailbox, a value from another Group, a limit override that loosens, or a settlement for a call that isn’t pending. Anything else is known only when the queue is drained, and comes back as a report.
- Worker calls:
Load,Reload,Extend,AddLibrary,ReplaceLibrary,Pump,Save,Fingerprint,Inspect,GrantsandCounters. They come from the one goroutine that pumps the Group. Two made at once are undefined in Go and not detected. - Reentry: a worker call made from inside the Group’s own Pump or a scope/Segment lifecycle callback or Grant release hook, including cleanup outside a Pump, is the Host error
reentrant callin both Cores. - Host functions: Operation functions, property
GetandSet, Segment lifecycle hooks and Grant release hooks run inside a Pump. Scope abandonment, Segment rollback and Grant release can also run during Reload or library replacement. They may make queued calls, subject to the lifecycle finalization rules.
Driving a TS Group
Section titled “Driving a TS Group”createGroup({ name, core?, ...driverOptions }) from @northtalk/ts creates a driven Group with close(reason?) and [Symbol.asyncDispose](), so a Host can write await using group = createGroup({ name: 'g' }), load a Script and await script.invoke(...). It uses the process-wide TS Core by default, or the supplied shared Core. The /wasm export requires core, obtained from its asynchronous createCore. The Helper is built on the shared embedding interfaces (ADR 0121, ADR 0130); it adds no members to the Core’s Group interface. It takes the same options as newDrivenGroup, owns onReady, and delegates close and disposal to the driver described below, including idempotency and the default reason Host shutdown.
Scripts loaded through this Helper have script.handlers.<name>(...args). Each argument passes through toValue(arg, { numbers: 'integer' }), the call uses script.invoke, and its answer passes through default fromValue: numbers become Decimals, maps plain objects, and kinds without a JS form stay Values. Conversion failures reject with invalid value naming the one-based argument position; invoke rejections pass through unchanged. then, symbols, Object.prototype names and invalid message names read as undefined, keeping the Proxy non-thenable; a valid undeclared name rejects as invoke does. group.load<T>() lets the Host state a type for handlers without runtime checking. The default takes PlainValue | number | bigint arguments and resolves with PlainValue. Both TS entry points also export handlersOf<T>(script) for any shared Script; its Requests still need the Script’s driver or Host Pump loop. The shared Script interface and invoke’s Value boundary stay unchanged.
inlineGrants({ cap: { op: fn | { fn, arity } | { async: fn, arity?, maxPendingMs? } } }), exported by both TS entry points, defines one Capability per outer key and grants all its Operations. The returned grants object can be passed to load or spread beside ordinary Grants. Each Operation has value argument and result Shapes, zero cost, no Argument Labels and command: true. Arguments pass through default fromValue, and results through toValue(result, { numbers: 'integer' }); a result conversion failure raises invalid value in the Script. A thrown ScriptError and other callback exceptions retain ordinary Host callback behavior. A plain function is immediate; { async: fn } suspends, with maxPendingMs defaulting to the Group’s maxWaitMs, and receives the call’s AbortSignal as its final argument. Arity is fn.length unless arity overrides it, including for async callbacks; Hosts should override it when their signal parameter contributes to that length. The existing argument-count and Host Command checks apply: ask math to sum 10, 10 and sum 10, 10 both answer in it, while a suspending command writes fetch id and wait (ADR 0130).
For a Host that runs from the event loop, newDrivenGroup(core, options) from @northtalk/ts/driver creates a Group on core, the TS Core or the Zig Host Adapter’s, with readiness already wired to its driver and returns { group, drive }. It takes the Group’s name, optional seed and trace, and the driver’s clock, pump, setDeadline, onPump and onError options. It owns onReady; the Host can queue Requests as soon as the factory returns.
The driver schedules one Pump on a later macrotask when input arrives, continues after a Fuel Slice or rewind, and arms a timer for the next deadline. Its default Clock reads epoch microseconds from Date.now() and clamps readings so they never go backwards. A Host supplying its own Clock also supplies setDeadline. onPump receives each Pump result after it returns, and onError receives a Pump exception. drive.idle() waits until no Pump is scheduled or running; waiting only on a deadline counts as idle. drive.stop() cancels scheduled Pumps and the deadline timer and ignores later readiness; it does not stop Scripts or settle their pending Requests.
autoDrive(group, options) remains available for a Group whose onReady calls drive.ready(). Hosts that use newGroup directly must supply a Pump loop for queued work to finish. Both drivers are helpers outside parity; they change no Core scheduling rules.
await drive.close(reason) stops every Script loaded when closing begins, drains their Stop inputs, waits for the Group’s outstanding Promise-returning run Operations to settle, drains their late answers or failures, then cancels scheduling. The default reason is Host shutdown. Stop aborts pending Operations, releases Grants and settles Requests as send failed, reason stopped; it does not run Script finally blocks. An Operation’s rejection during shutdown is an ordinary late failure, not a failure of close. Promise work already abandoned by a timeout, cancellation or Reload is also awaited. Callback-style start Operations receive the aborted signal but have no completion Promise for the driver to await; the Host owns any further cleanup.
Before closing, the Host stops admitting work, including new Scripts and Reloads. Closing is idempotent: repeated calls share one Promise and the first reason. It works after drive.stop() too, restarting scheduling only to finish shutdown. Calling stop() during a close does not interrupt it. A Clock, Pump or driver callback failure rejects close and cancels scheduling; shutdown may be incomplete. A Host run Promise that ignores cancellation and never settles keeps close pending; the driver imposes no timeout and cannot force Host I/O to finish. drive.idle() retains its narrower scheduling-only meaning.
The driver implements [Symbol.asyncDispose]() as close(), so a Host can use await using drive = newDrivenGroup(core, options).drive to close at scope exit. This syntax requires runtime support for Symbol.asyncDispose; the driver declarations reference TypeScript’s ESNext.Disposable library. Both explicit close and disposal finish before the Host releases resources the Operations use.
Time and reports
Section titled “Time and reports”- The Clock is an argument:
Pump(now, …)takes the Group’s one Clock reading, andCall.Now()returns it. A reading earlier than the last Pump’s isclock backwards. A game pauses by not pumping, and freezes time by passing the samenow. TS’snowMicros()readsDate.now()as epoch microseconds for a manual Pump; unlike the driver’s Clock it does not clamp. - Reports are returned, never called back: a Pump returns its reports as one ordered list, and
RequestandCallfutures settle as it finishes. Calls that end Runs outside a Pump (ReloadandReplaceLibrary) return their reports; Restore returns the accounting baseline inRestoreResult.reports. - The report kinds:
charge result, withrequest,call, requestedfuelandstatus(accepted,limit,inactive), in input-drain order before resulting terminal reports (metering)run end, carrying its delivery id and any broadcast id. A Run that a Fallback Handler clause ran setsfallback, and itshandleris the message’s Selector. AnerroredRun’s error reaches the Host as aScriptError: itscode, its textmessage, and its other fields as its data. Itsatis the raise that no Unwind Table entry caught, the Run’s lastraiserecord, and a Limit Fault’s is its faulting instruction, thefaultrecord’s: each gives the code unit, the frame’s Handler as an error’satnames it, the instruction index and the source position. Other outcomes have noatstopunhandledcall failed, which carries the Host-side detail of ahost errorthe Script saw. If Stop or cancellation interrupts the Run at a property crossing, a getter or setter failure neither raiseshost errorin the Script nor emitscall failed; the property’sproperror record is still written. If Stop or cancellation interrupts the Run at an Operation crossing, a Host failure neither raiseshost errorin the Script nor emitscall failed; thecallrecord is still writteneffect failure, carrying Script, Run, named Grant, Segment, phase (abandon,begin,commit,rollback), status (failed,unknown), scope for abandonment, and optional Host-only detail;effect failedRun reports also identify the failure that prevented commitdecided, carrying a Decision’s Verdict (below)- the lifecycle and cumulative Run accounting reports
Run accounting
Section titled “Run accounting”ADR 0065 adds public accounting for every Host, not an opt-in debugger or Session callback. It is always returned by Pump, Reload and ReplaceLibrary in their reports, and by successful Restore in RestoreResult.reports. Stop is queued and reports through Pump. A refused operation creates no accounting records. The declarations in talk.go and talk.ts are authoritative.
| Report | Fields beyond its discriminator | When |
|---|---|---|
run started |
script, run, rootDelivery, optional parentRun, parentCall, delivery, either selector or fn, args |
A new Run dispatches, before any execution in that Run. |
run discarded |
script, run, rootDelivery, optional parentRun, parentCall, reason |
A live Run is discarded without an ordinary run end. |
run accounting |
script, run, rootDelivery, optional parentRun, parentCall, cumulative fuel, state |
Once per affected Run at the end of the Host call. |
causal work |
rootDelivery, liveRuns, queuedMessages, cumulative discardedMessages |
Once per affected root at the end of the Host call. |
- Lifecycle order:
run startedandrun discardedjoin ordinary reports in actual occurrence order; existingrun endremains the terminal event for normal outcomes and is not duplicated. Runs starting and ending within one call still have both events. A discarded Run’s reason is exactlystop,reload,library replacement,variables-only restoreorrewind. A message that never starts a Run has no invented Run id or lifecycle event. - Accounting tail: after lifecycle reports append one
run accountingfor every Run started, charged, ended or discarded in this call, ordered by Run creation order, then onecausal workfor every changed root in root Delivery admission order. The former’sstateislive,terminalordiscarded. Updates are cumulative replacements, never deltas. Include charges for message-observation tests, restored-call Reissue, cleanup and failing work, even if no Segment or ordinary terminal Trace record was emitted. Discard captures Fuel before removing the Run. A call without relevant changes has no accounting tail. - Ancestry: each Host Delivery starts a new root identified by its delivery id. Runs and queued messages spawned from a Run inherit its root.
parentRunis the spawning Run even if it ends before dispatch; a call also suppliesparentCall. Message Path forwarding retains ancestry rather than creating a Host root. Implicit error Handlers inherit the failed Run’s root. Broadcast recipients use their individual Delivery ids. Host timer/Notification Deliveries and actions queued by external Host callbacks are new roots, not descendants of the Script that provoked them. Answering a Capability or firing a Run’s wait deadline resumes its existing ancestry. - Pending work: include messages admitted to the input queue or mailbox that have not yet been consumed, dispatched, rejected or dropped. Waiting/parked Runs count as live, not queued messages. Forwarding transfers a queued message without counting it twice. Observation by an already-existing
wait forRun does not consume the message: normal routing/dispatch still follows. It does not reparent the waiting Run or charge that Run’s observation work to the sender’s family.discardedMessagesincreases only when lifecycle Stop/Reload/replacement/variables-only restore removes queued work; cancellation or ordinary dispatch rejection does not increase it. Emit a final zero-live/zero-queued record, even for a root that never obtained a Run. A consumer must not infer completion from a root Run ending or from Group quiescence. - Between calls: queued Host inputs can be admitted without returning reports. Their initial queue observations are returned on the next report-returning worker call; no execution or Fuel is hidden in that interval. A save preserves this pending accounting state. Queries of cached reports describe the last completed observation boundary.
- Restore baseline: a successful full Restore reports all saved live Runs’ accounting and all saved active roots’ causal counts, without replaying their original
run startedevents. Variables-only Restore first reports saved Run discards and their exact saved Fuel, then root counts with discarded queued messages and no live work. Rejected Restore reports no successful baseline. Saved ended Runs need not be re-emitted: a Host restoring aggregate measurements saves its own accumulated totals alongside the Group. Restore replaces a timeline; never merge totals solely because restored ids equal previously used ids. - Observational: producing these records charges no Fuel or allocation, does not alter scheduling and adds no canonical Trace lines. It must not call
Inspect()or introducevarsHost Inputs. Direct API tests compare reports across Cores; Trace equality alone cannot verify them. Counters and ancestry needed for future reports are part of saves; emission buffers contain only observations not yet returned and must not replay already-returned lifecycle events.
Values at the boundary
Section titled “Values at the boundary”Each Core gives the Host one opaque, tagged Value type. A Host builds values only through named constructors and reads them only through accessors, so every conversion follows a rule this section states (ADR 0030).
- Refused, never repaired: input the value model can’t hold is refused at the constructor, as the Host error
invalid value. Nothing is clamped, rounded or replaced, so a Host bug surfaces at the Host’s own call. - Numbers in:
Int,Uint,FromFloatandDecin Go, andnumanddecin TS.- A float becomes the shortest decimal that reads back as the same float, the digits ECMAScript’s
Number::toStringand Go’sstrconv.FormatFloat(f, 'g', -1, 64)both give, so0.1stays0.1. - NaN, ±Infinity, more than 34 significant digits and a magnitude of 10^34 or more are refused (chapter 3).
-0.0enters as0. Decanddecread text exactly asas numberdoes, one leading-included (chapter 3).
- A float becomes the shortest decimal that reads back as the same float, the digits ECMAScript’s
- Numbers out: a number reads as an opaque
Decimal. ItsString()is the canonical text, trailing zeros kept. An integer read fails unless the value is an integer that fits, and the float read rounds to nearest, ties to even. - Text: text that isn’t valid UTF-8 (Go), or a lone surrogate (TS), is refused. Text is normalised to NFC when the
Valueis built, uncharged, and text going out is always NFC. - Maps: keys are text. Order is the order the Host gives, and
Entries()returns insertion order. A duplicate key, compared after NFC, is refused. TS’srecord(obj)refuses integer-like keys, since JS reorders them. - The other kinds:
- Nothing is
northtalk.Nothingin Go and thenothingconstant in TS. The named constructors never acceptnullorundefinedfor it. - A Quantity is built from a
Decimaland a Unit spelled as a Script spells it ("kg"), and reads back as its number and its canonical Unit. An unknown Unit is refused. - A Civil Date is built from fields, or from text in the
as civil datesyntax, and an invalid date is refused. An Instant is built from seconds since the Unix epoch and microseconds from 0 to 999999, and anything outside that range is refused. In Go it can also be built from atime.Time, dropping its monotonic reading and zone, and truncating toward the past to the microsecond (ADR 0091). No native type is ever read as a Civil Date. - Bytes are copied in both directions.
- A range is built from two ends as
..builds one, and reads back as its two ends (ADR 0034). - A Path is built from its steps, each a key or a non-zero integer position within the position limit, 2³¹ − 1, and reads back as them, so a Host can hold it as its own path type. Any other step is refused (ADR 0184).
- A Text Pattern can only be passed back unchanged. Its canonical source can be read, for display.
- A Function Value is opaque. Its Home Script and display form can be read (Function Values).
- A Host Object is its own handle type, with the Host’s id.
- Nothing is
- The display form:
String()andtoString()give the display form (chapter 11). - Adding:
Add(a, b)in Go andadd(a, b)in TS apply the+rules of chapter 3 outside any Run, uncharged. Where+would raise, they fail with that error as aScriptError, with its code and fields. AstoreHost appliesincrementdeltas with them, so every Store adds as Scripts do (chapter 7). - Plain JS data: TS also has
toValueandfromValue, which convert between Values and plain JS data by the named constructors and accessors (ADR 0119).toValuereadsnullandundefinedas Nothing, arrays as lists, plain objects asrecorddoes, and aMapasmapdoes. It refuses a JSnumberby default;{ numbers: 'integer' }accepts only safe integers throughnum, while{ numbers: 'decimal' }appliesnum’s shortest round-trip rule. Other numbers in integer mode throwinvalid valuenamingdec()and{ numbers: 'decimal' }.fromValuewrites Nothing asnull, a number as aDecimal, a list as an array and a map as a plain object, or as aMapwhen asked. Every other kind comes back as theValue.
Zone Rules builders
Section titled “Zone Rules builders”Each Host API offers a builder that makes Zone Rules from the Host’s own zone data, given an IANA zone id and a window from one Instant up to another (ADR 0179). It is uncharged and runs outside any Run.
- Result: an ordinary map Value with the shape chapter 7 gives.
zoneis the id as given. The first change’satis the window’s start and holds the offset in effect then, each later change is an Instant in the window where the offset changes, anduntilis the window’s end. - Failures: an unknown zone id, an empty window, or a window the Host’s zone data doesn’t cover fails at the builder, so a Host learns of a bad zone before any Run uses it.
- Agreement: for every Instant in the window,
toCivilandtoInstantwith the result give what the Host’scalendarimplementation gives for the same zone, if the Host offers one.
JSON and the Value Encoding
Section titled “JSON and the Value Encoding”- Plain JSON:
DecodeJSONandEncodeJSONfollow the JSON mapping of chapter 7, the rule thejsonLibrary follows. Numbers are read from their text, never through a float. - The Value Encoding is the lossless JSON form of every kind that can be encoded, for Host storage and the message layer. The same value always gives the same bytes: UTF-8 JSON with no white space, with strings escaped as the Group Fingerprint’s are, and a JSON number written as its canonical text.
- Booleans are JSON booleans, text is a JSON string, Nothing is
null, and a list is an array. - A number with no fraction digits in its canonical text (so
3, but not3.0) and a magnitude below 2⁵³ is a JSON number, and every other number is{"$dec": "<canonical text>"}. So trailing zeros survive. - A map is a JSON object, in order. A map with any key starting with
$is{"$map": [[key, value], …]}, so a key never reads as a tag. - The tags are
{"$quantity": ["2.50", "GBP"]}, with the number’s canonical text and the Unit in normal form, every word Unit singular (["3", "day"]),{"$bytes": "<base64, padded>"}, with the standard alphabet and the bits padding leaves over zero,{"$range": [from, to]},{"$path": [step, …]}, with each key a JSON string and each position a JSON number,{"$instant": "<RFC 3339 in UTC, with the shortest fraction, at most six digits>"},{"$date": "<the as civil date form>"},{"$pattern": "<canonical source>"}and{"$object": [kind, id]}. - A Text Pattern is re-parsed when decoded, and a Host Object is found through the Host’s resolver.
- Decoding accepts only these forms. A value decodes only if encoding it gives back the numbers, tags and payloads the input wrote, so it is refused, never repaired, as
invalid value. A number is its canonical text, and one that fits a JSON number is never$dec({"$dec": "3"}is refused).$mapholds only a map with a$key, every tag’s payload has the form above, and Base64 has no other padding or alphabet. JSON white space and string escapes are syntax, not form, and text is normalised to NFC as the Text constructor does. - Function Values can’t be encoded for storage, since a Host-held handle isn’t durable. Only the message layer carries them.
- Booleans are JSON booleans, text is a JSON string, Nothing is
- Scripts can’t reach the Value Encoding, and the Conformance Corpus uses the display form instead (ADR 0018).
Canonical decoding examples
Section titled “Canonical decoding examples”Each input in the left column is refused as invalid value. The right column shows the form the encoder writes for that value; the decoder never substitutes it for the refused input.
| Refused input | Encoder form |
|---|---|
{"$dec":"01"} or {"$dec":"3"} |
1 or 3, respectively |
1.0 |
{"$dec":"1.0"} (the fraction digit is retained) |
-0 or 1e2 |
0 or 100, respectively |
{"$quantity":["3","days"]} |
{"$quantity":["3","day"]} |
{"$instant":"1970-01-01T01:00:00+01:00"} |
{"$instant":"1970-01-01T00:00:00Z"} |
{"$instant":"1970-01-01T00:00:00.500Z"} |
{"$instant":"1970-01-01T00:00:00.5Z"} |
{"$instant":"1970-01-01T00:00:00.0000001Z"} |
none: seven fraction digits are finer than a microsecond |
{"$date":"2026-09-27T00:00:00.0"} |
{"$date":"2026-09-27T00:00:00"} |
{"$map":[["a",1]]} or {"$map":[]} |
{"a":1} or {}, respectively |
{"$bytes":"AB=="} |
{"$bytes":"AA=="} (unused padding bits are zero) |
JSON syntax and NFC normalisation are exceptions to byte identity: { "a" : "\u0065\u0301" } is accepted and encodes as {"a":"é"}. Map insertion order is retained. These decoding rules apply recursively to values inside lists, maps and tag payloads, and do not change the plain JSON mapping. Value Encoding cases in the Corpus test the encoder; each Core’s unit tests carry the decoding refusals (ADR 0030).
Shapes
Section titled “Shapes”An Operation Declaration gives a Shape for each argument and for its result. Shapes cover every kind, Quantities by Unit or by Unit Kind, lists of a Shape, closed and open maps, Host Objects of a kind, a choice (OneOf) and an optional value.
An Object Shape accepts only a Host Object whose Object Kind has the declared name, including a disposed handle. A mismatch writes that Object Kind name as expected; got remains the value’s kind ("object" for a Host Object of another Object Kind). Host Objects have no Script literal form, so a literal argument to an Object Shape is refused at load; dynamic values are checked at run time.
any accepts every data value, but refuses Function Values, including nested ones, with not encodable. value accepts every value, including Function Values at any depth. Console’s write uses value so a Script can show any value’s text form. Acceptance by a Shape does not make a Function Value durable: the Value Encoding still refuses it.
An Optional Shape accepts either its inner Shape or Nothing. In an Operation’s argument list, a suffix of Optional Shapes may also be left off the call. Only an outer Optional wrapper makes a position omittable: a choice containing an Optional Shape still requires its argument, and an Optional Shape before a required one still requires its positional slot. For [text, Optional(number), Optional(text)], a call supplies one, two or three arguments. Too few required positions or too many arguments is wrong argument count at load, including calls inside Libraries.
The Host function receives only the arguments supplied, in order. The Core inserts no placeholders or defaults; an explicit Nothing remains a supplied argument. The call record and a pending call’s arguments keep that same list, including through save, restore, Reissue and Adopt. Only supplied arguments are checked against their Shapes, and the Operation’s declared cost is charged for every call regardless of how many Optional positions are omitted. The call instruction’s argument count and its Cost Model terms use the supplied count. say still requires exactly one source argument, even if a Host grants a custom console.write declaration with Optional arguments.
In TS the Host function takes each checked argument in its Shape’s JS form (ADR 0120). Text is a string, a boolean a boolean, a number a Decimal, Bytes a copied Uint8Array, an Instant its epoch microseconds as a bigint, Nothing null, and a Host Object its handle. A supplied Nothing for an Optional Shape is null, and an omitted argument is absent. Every other Shape gives the Value. A result may be the result Shape’s JS form, a bigint for a number, or any Value. The Core converts it by the named constructors before it checks the result, so a JS form the Shape doesn’t name fails the check as any wrong result does. call.answer takes the same forms. The types follow from the declared Shapes, so a callback needs no asText()!. Go Hosts still take and return Values.
- At load: the loader checks each call’s argument count, the literal keys of a closed map, and the kind of every literal argument. There is no inference beyond literals.
- At run time: the Core checks each argument before the Host function runs. A mismatch raises
wrong kindin the Script, the Host function never runs, and nothing is charged (chapter 6). - Results: a result that breaks its Shape is the Host’s fault. The call ends as
host error, and the detail goes in acall failedreport. - Messages have Shapes only in the Host Manifest, for tooling. The Core never checks a Delivery against them.
- From a Script: the Built-ins
conforms,checkandexplaincheck a value against a Shape written in this same data spelling, with this same acceptance, under the Script’s own budgets (chapter 7). They change nothing at this boundary: a Capability argument is still checked as above, uncharged, whatever a Script checked earlier. - From a Host:
conforms(value, shape)andexplain(value, shape)check a value against a Shape the Host built, with this same acceptance (ADR 0176). They are pure: they need no Group, charge nothing and write nothing to a Trace.conformsgives true exactly when the value fits.explaingives theexplainBuilt-in’s report as a Value: a list of every mismatch record, in its order, empty when the value fits. The Shape constructors already refuse a malformed Shape, so neither function raisesinvalid shape.
Capabilities
Section titled “Capabilities”- Defining one:
DefineCapabilitytakes a name and its Operations, once per process. Each Operation is a declaration (name, argument Shapes and optionallabels, result Shape, cost, mode,maxPending, declared error codes, optionalscope,segmentBoundandcommandmetadata, and an optionaldescriptionandexamples) paired with the Host function that implements it. Declarations are ordered by name, whatever order the Host gives.ask,tell,sendandwaitare refused as Operation names. - Argument Labels: an Operation’s
labelslist one word for each argument after the first, so a call may write them between its arguments, leaving out an Optional argument’s label along with the argument (ADR 0160): withlabels = ["to"],ask world to move "pass" to "red hangar"callsmoveasask world to move "pass", "red hangar"does (ADR 0115). Each must be an Argument Label word, and the list has one entry fewer thanargs;DefineCapabilityrefuses anything else asinvalid value. An empty list is the same as none. The labels don’t change the Operation’s name, so they are checked only at load (chapter 4): the call, itscallrecord, the Trace and the Host function see only positional arguments. Labels are part of the declaration, so the Host Manifest, the Group Fingerprint, saves and restore’s declaration matching carry them. - Host Commands: an Operation marked
commandmay also be called as a Host Command, by its name alone.DefineCapabilityrefusescommandon an Operation whose name is a Reserved Word. The flag is part of the declaration, so the Host Manifest, the Group Fingerprint, saves and restore’s declaration matching all carry it, and withGrantsAsUseda Host Command call is a use of its Operation (ADR 0094). - Documentation: an Operation’s
descriptionis plain text and itsexamplesare a list of NorthTalk source texts, each calling the Operation, for tooling to show (ADR 0077). An empty description or list is the same as none. Adescriptionthat isn’t text, orexamplesthat aren’t a list of text, are refused. The Core never parses or checks the text, and only the Host Manifest carries it: the Group Fingerprint, saves, restore’s declaration matching and the Trace leave it out. The Standard Capabilities’ declarations have none. - Modes:
- Immediate:
Doruns at the call, inside the Run, and returns the result. - Suspending:
Startruns at the call and returns at once, and the Host answers later withAnswer,AnswerWithCostorFail, from any thread. - Fire-and-forget:
Fireruns at the call, in order, and its result is dropped. Only these can be called withtell … to. Atellblock calls each Operation in its own mode (ADR 0063).
- Immediate:
- Grants: a Grant is a set of a Capability’s Operations with the Host’s own binding data, which each call reads.
Loadbinds Grants by the name the Script uses, so one Capability can be granted twice under two names with different bindings. Each Load copies its kept Operation set without changing the reusable Grant template. - Grants as used: with
GrantsAsUsed, a Script keeps only the granted Operations it and its Libraries use, including unused definitions, Lambda bodies, every imported Library’sneedsand implicit abandonment dependencies;sayusesconsole.write. This trimming happens once at Load, after validation, and removes names whose kept set is empty. Reload, Extend and Library replacement cannot regain an Operation it discarded. - Grant inspection: the Script’s
Grantsreturns a fresh map of its kept names to Operation names, including disabled Grants and Grants that are revoked but not yet removed by Reload. Each Operation list is sorted in Unicode code-point order. Map-key enumeration follows the Host language: Go maps have no iteration order, and TS records enumerate integer-like names numerically before other names. - Standard Capabilities:
clock,calendar,locale,timer,console,store,sqlite,user,httpandpeerhave their declarations fixed by chapter 7. Their factories take Host implementations, except forclock, and a cost map keyed by Operation name. Every Operation must have its own cost entry, with Fuel required and allocation zero if absent. Both components must be whole numbers from 0 through 9,007,199,254,740,991; a missing or invalid cost is a Host Errorinvalid value. Extra Operation names in the cost map are ignored. The factory copies each declared cost, so later changes to the map or its entries do not change the declaration. Atimerimplementation must supply bothscheduleandcancel, and aconsoleimplementation bothwriteandread, acalendarimplementation all six of its methods, alocaleimplementation all eight, astoreimplementation all eight Operations, all three lifecycle hooks andrelease, asqliteimplementation all five Operations andcoordinator, auserimplementation all four Operations, anhttpimplementation all three server Operations,fetch, or both, and apeerimplementation all five Operations; a missing method is alsoinvalid value. Every Core defines every Standard Capability, and a Host offers the optionalsqlite,user,httpandpeeronly by calling their factories. - The
storefactory: its Grant’s binding is the Store’s name, as text.set,delete,incrementandswapare declared Segment-bound, so the factory maps every binding to the implementation as one Segment Coordinator, whosebegin,commitandrollbackreceive each enrolled Store’s Grant name and binding (the lifecycle contract). The factory takes no quotas: the implementation sets and enforces them, with the reservations chapter 7 requires. The Core checksinvalid key,invalid watchvalidation and the result kinds.watchandunwatchare immediate and not Segment-bound; the factory passes the effective message (storeChangedfor omitted or Nothing) towatch, preserves the supplied arguments in the Trace, and forwards the implementation’s release hook. Everything else about the Store is the implementation’s obligation. The Store implementation’s coordinator is the implementation itself in TS, andStoreCoordinator(impl)gives it in Go, so asqliteimplementation can share it. - The call: a Host function gets a
Call, which gives the call id, the Script’s name, the Grant’s binding, the Pump’s Clock reading, the delivery id of the Host Delivery that started the calling Run when one did (ADR 0125), and a context or signal that is cancelled when the call is abandoned. It never reads the Host’s own time. - Charging:
- The declared cost is charged before the Host function runs, and a Run that can’t cover it has a Limit Fault at the call.
Chargedraws more Fuel before work during the Host callback. An unmarked Operation charges up front; a Metered Operation may authorize successive chunks. Refusal latches a Limit Fault even if suppressed; the Host stops without doing that chunk, and prior accepted charges remain spent.- An additional cost not already paid travels with the answer,
AnswerWithCost, and is charged when the Run resumes, where it can fault. - Converting a result into Script values is charged to the Run (chapter 8), and so is converting a
Fail’sData, as a result is.
- Failing: a
Fail, or a returnedScriptError, raises its code in the Script, with its message and itsData’s entries as fields (chapter 6).Datamust be a map or Nothing. Any other value is a malformed Host failure: the Script raiseshost error, and the Host-side detail goes only in thecall failedreport. This applies to Operations and Object property getters and setters. A catalogue code the Operation doesn’t declare, a code outside a declared list, or aDatakey that is reserved, also becomeshost error. So does any other error the Host function returns. - Waiting: a suspending call past its
maxPending, or else the Script’sMaxWait, fails withtimeoutand is abandoned. An answer or failure for a call that isn’t pending, because it was abandoned, its Run has ended or a restore discarded it, is recorded and ignored. - A
Callbelongs to its Group: itsAnswerandFailreach only the Group that made it, never a Group restored from a save of it. A restored Group is answered through theCalls thatSettlereturns, and only the message layer’sanswerandfail, which name the Group and the call id, can reach it for a call it no longer holds (chapter 10). - Revoking:
Revoketakes effect when its queued input is drained. It affects only that Script’s named Grant, makes later calls through it raisecapability revokeduntil the next Reload, and makes them load errors after it. Calls in flight and their cancellation signals are left to the Host. Repeated revocation and revocation of a name the Script doesn’t keep do nothing, but are still recorded. Reload validates with revoked Grants removed, and removes them only if it succeeds; a rejected Reload leaves the old code, kept Grants and revocation state intact. Library replacement applies this same rule at each affected Script’s Reload boundary. Extend leaves existing code and Grants intact, but checks the new source against unrevoked Grants.
Metered Operations
Section titled “Metered Operations”The metering contract defines declaration eligibility, synchronous chunks, queued asynchronous requests and their futures/reports, FIFO admission, refusal, accounting, save restrictions and replay. metering is optional read-only or segment-bound; omission preserves existing charging. Only read-only suspending Operations can request Fuel while pending. The Host waits for an accepted outcome before doing the next chunk, subject to cancellation.
The Grant release hook
Section titled “The Grant release hook”A Capability may supply a release hook. The Core calls it synchronously when one Script’s named Grant stops being effective, and the Host drops everything it holds for that owner. The store factory passes the implementation’s release hook, which forwards to the router.
The hook receives the Group’s identity, the Script’s name, the named Grant, its binding, the Group’s last Clock reading and a reason:
| Reason | When the Core calls it |
|---|---|
stop |
the Script is stopped: a Host Stop as it lands, disposal of its owner, or every Script when fatal effect uncertainty stops the Group |
reload |
a Reload of the Script, or a Library replacement that reloads it, succeeds |
revoke |
a revoke Host Input for that named Grant is drained, the first time only |
disable |
failed automatic abandonment disables that named Grant |
- Which Grants: for
stopandreload, the Core calls the hook for every named Grant the Script keeps whose Capability supplies one, in Unicode code-point order of the names. Grants already released byrevokeordisableare included, since the hook is idempotent for the Host. - When, relative to other cleanup: for
stopandreload, after abandoning the Script’s scopes and rolling back its participant, and before thestopreport, the replacement code or any later execution. Fordisable, right after theeffect failurereport for the failed abandonment. Forrevoke, when the input is drained, before anything later in that Pump. - Not released: a rejected Reload or Library replacement, an Extend, a repeated revocation, a revocation of a name the Script doesn’t keep, or Save. A Restore never calls the hook: the new Group’s routing is set up by checkpoint restore.
- Its contract: like the Segment lifecycle hooks, it is Host work with no Script result, cost or Trace record. It runs inside a Pump, or within
ReloadorReplaceLibraryoutside one. It may queue inputs but can’t make worker calls, which arereentrant call. It returns nothing, and the Core ignores anything it throws or panics with, because releasing can’t be refused. Its timing follows records the Trace already has, so a replay calls it at the same points. - On the message layer: the Core sends
releaseas an interim reply topump,reloadorreplace-library, withscript,grant,reasonandnow, and the Host answersrelease-resultwith no fields.
In TS, defineCapability takes an optional fourth ReleaseHook argument, independent of its Segment lifecycle argument. In Go, DefineCapability, DefineSegmentCapability and DefineCoordinatedCapability take Operation declarations and WithReleaseHook(func(GrantContext)) as CapabilityOption values. The Host Manifest and Group Fingerprint include the Operation Declarations and exclude the hook.
The musical clock
Section titled “The musical clock”A Host whose Scripts keep musical time, such as Folio with its Transport, supplies a musical clock when it makes the Group (ADR 0166). It is a Capability with one suspending Operation, wait, whose one argument has the Shape {"oneOf": [{"unitKind": "bar"}, {"unitKind": "beat"}]} and which has no maxPending.
- The call: a Script’s
wait 8 barscallswaitwith8 bars, as anask … and waitwould, through a Grant every Script of the Group holds under the reserved namemusical-clock. A-can’t be part of a Name, so no source can name that Grant, soask,tell,revokeandGrantsAsUsednever see it. Everything else follows from its being a pending call: itscalland answer records in the Trace, its place in a save, its abandonment on Stop, Reload and cancellation, and the release hook’sstopandreloadcalls. - The answer: the Host answers Nothing when the line is due. A failure raises in the Run as any Operation’s failure does.
- Without one,
waitin a Musical Unit raisesno musical time(chapter 5). - Making one:
DefineCapabilityrefuseswaitas an Operation name, so the Core makes the musical clock from the Host’swaitfunction, the Operation’s cost and an optional release hook: in TSmusicalClockCapability(impl, costs, release?), in Go(*Core).MusicalClockCapability(impl, costs, options...), and in Ctalk_musical_clock_capability. Its Operation declares no error catalogue, so any failure the Host gives raises in the Run. On the message layer the Host sends it withdefine-capability’smusicalClock: trueinstead ofstandard, and the Core supplies the fixed declaration. - Supplying one: in TS the Group option is
musicalClock, and in GoWithMusicalClock(clock), aGroupOptionthatNewGroupandRestoretake. A C Host, and a message-layer Host, grants the clock to each Script undermusical-clockat load and restore. The Group Fingerprint includes its Operation Declaration; the Host Manifest writesmusicalTime: trueinstead.
The notification router
Section titled “The notification router”Each Core supplies a router as a helper built only on this interface, at @northtalk/ts/notify in TS and northtalk.org/go/notify in Go. As with the drivers, its idiom is outside parity, but the Store registration, routing and lifetime rules, watch limits and checkpoint rules apply to it. A Host with its own storage builds a StoreImpl around it:
The helper’s TS and Go declarations are in talk.ts and talk.go. RouterOptions supplies the Store’s limits and current revision, and an optional admission callback. RoutingResult lists restored, dropped and resynced watches as <script>.<grant>.<watch>, in the order of watches. pumped(group) is called after each Pump returns and gives true while the Group still has pending work.
In Go, notify.New(RouterOptions) returns a *Router, whose methods have the same roles. RouterOptions has the same members, with Admitted func(*talk.Group). Commit takes apply func() ([]string, error); a returned error routes nothing and is returned unchanged. Save returns checkpoint bytes and an error; Restore returns the Group, RestoreResult, RoutingResult and an error. The full declarations are in talk.go. A Host that pumps for Notifications, as the Session Host does, learns of them through admitted.
changed(before, after) in TS and notify.Changed(before, after) in Go compare Value Encoding bytes for the Store’s net-change test, treating a missing key and Nothing as one state.
The router owns each Store’s synchronization, so a Store applies every commit, including Host-originated ones, through commit. Revisions, checkpoint bytes and the router’s internal layout are each implementation’s own, and a checkpoint restores only through the router family that took it, as a save restores only on its own Core family.
A later Host-owned source reuses the router’s ownership, release, admission, ordering, overload, retry, limits and checkpoint rules. It defines its own watch parameters, matching rule, payload fields and revision. Script-authored publication stays deferred (ADR 0061).
The sqlite factory
Section titled “The sqlite factory”A Host that offers the optional sqlite calls SqliteCapability in Go or sqliteCapability in TS, with an implementation, the cost map and a per-step Fuel cost (ADR 0070). The Core does everything chapter 7 states about values, rows, max and scopes, and the implementation does what SQLite must: run the statement, keep the database’s transactions and enforce the rules under Host obligations.
- The binding is
{database, tables, maxRows}.databaseis the Host’s name for the database, and a Script never sees it.tablesis optional: when present, it lists the tables the Grant may use, and when absent, the Grant may use every table but a co-located Store’s.maxRows, the row cap, is a whole number from 0 through 9,007,199,254,740,991. A binding that breaks these is Host Errorinvalid valuewhen the Grant is created. - The per-step cost is a whole number of Fuel from 0 through 9,007,199,254,740,991, and anything else is Host Error
invalid valuefrom the factory. It is an argument of its own, not a cost-map entry, since the cost map ignores names that aren’t Operations. - Charging:
queryandchangecharge their declared cost, then authorize every statement step through a factory-suppliedbeforeStepcallback that drawsperStep. Query is read-only metered; change is Segment-bound metered. The driver calls the callback before every step, including completion and overflow probes, and stops on refusal. See SQLite step authorization; the factory does not prechargemax. - Coordinators: the factory calls the implementation’s
coordinatorwith a Grant’sdatabaseonce, when the Grant is created, and the implementation gives the same coordinator for the same database.change,begin,commitandrollbackare declared Segment-bound, so every Grant on one database shares one participant (the lifecycle contract). A Host that keeps its Stores in a database gives the Store implementation’s coordinator for it, so a Segment can write to both. - Scopes:
beginis declared to opentransactionwithabandon = rollback, andcommitandrollbackto close it, so the Core keeps the scope’s slot and abandons it as the lifecycle contract requires. - SQL values: the implementation sees
NULLasnilin Go andnullin TS,INTEGERasint64andbigint,REALasfloat64andnumber,TEXTasstring, andBLOBas[]byteandUint8Array. The Core convertsparamsinto these by the rules of chapter 7, a list into a positional list and a map into a name map, keyed without the colon.paramsis declared with the Shapeany, so a Function Value anywhere in it raisesnot encodable. After the Shape checks, the Core checksmax, then thatparamsis a list or a map, then each value in it, in order. Either of another kind raiseswrong kindas a Shape check would, withargument2:paramsitself withexpected"list or map", and a value in it withexpected"nothing or number or text or bytes or boolean"andpathits position or key. - Results: the implementation gives
{columns, rows}, each row a list of SQL values in column order, andchangealso giveschanges. The Core converts each value and builds each row’s map in column order. It raisessqlfor a column named twice, withreason"duplicate column "and the name, andunrepresentablefor a double it can’t hold, and for a string that isn’t valid UTF-8 in Go, or holds a lone surrogate in TS, each withcolumnits column’s name. A column name that isn’t a string, or in Go isn’t valid UTF-8, a value of another type, a row whose length isn’t the number of columns, more rows thanmaxor a negativechangesends the call ashost error. Neither error the Core raises here carries amessage. The Core checks the result’s form first, then its column names, then each value, row by row in column order, and raises the first failure it finds.
sqlite Host obligations
Section titled “sqlite Host obligations”An implementation meets each rule below, and a Host kit holds it to them. Each failure it reports is a ScriptError with the code and fields given.
- One statement: a call’s text is exactly one statement. Anything after it but white space and comments fails with
sql, and nothing runs. - Bound parameters: parameters are bound through SQLite’s binding interface, never spliced into the statement’s text. A list binds
?and?NNNin order, and a name map binds:name. The number of parameters given must equalsqlite3_bind_parameter_count. A statement with@nameor$name, one that mixes positional and named placeholders, a name map for positional placeholders and a list for named ones all fail withsql, and nothing runs. - The authorizer denies
BEGIN,COMMIT,ROLLBACK,SAVEPOINT,RELEASE,ATTACH,DETACH,VACUUM INTOandload_extension. It allows only the read forms of thePRAGMAstable_info,table_xinfo,index_list,index_info,index_xinfo,foreign_key_listanduser_version, and denies every otherPRAGMA. It denies reading or writing any table outside the binding’stables, and a co-located Store’s table, for reads too. A denial fails withsql, and nothing runs. - Read-only queries:
queryprepares its statement and checks it withsqlite3_stmt_readonlybefore stepping it. A statement that could write fails withnot read-only, and nothing runs. - Row limit: a call gives at most
maxrows. Its statement is stepped no further thanmax + 1rows, and one that gives more fails withtoo many rows, withmax. - Atomic calls: a call that fails leaves the database as it was before the call, including a
changethat fails withtoo many rowsafter its changes were made. - Constraints: a broken constraint fails with
constraint, withkindfrom SQLite’s extended result code:unique,primary key,not null,check,foreign key,datatypeortriggerforSQLITE_CONSTRAINT_UNIQUE,_PRIMARYKEY,_NOTNULL,_CHECK,_FOREIGNKEY,_DATATYPEand_TRIGGER, andotherfor every other. - Other errors: any other SQLite error fails with
sql, withreasonSQLite’s error message. - Text out: in TS, the implementation decodes
TEXTas UTF-8 with a decoder that fails on invalid input, andTEXTthat isn’t valid UTF-8 fails withunrepresentable, withcolumnits column’s name. It never gives a replacement character. - The Segment’s transaction: the coordinator’s
beginhook only prepares the Segment’s state and never takes a lock, since a failedbeginhook raiseshost error. The Segment’s firstchangeorbeginopens its database transaction and takes the database’s write lock.commitpublishes the transaction, androllbackdiscards it. Acommitthat SQLite refuses, such as for a deferred constraint, returnsfailed. - Script transactions: the
beginOperation opens a savepoint inside the Segment’s transaction,commitreleases it androllbackrolls back to it and releases it. - Contention: a
changeorbeginthat needs the write lock while another Segment holds it fails withsqlite busybefore anything changes. It never waits for the lock. - Reads: a Segment that holds the write lock reads its own uncommitted changes, and every other call reads the last committed state. A read never waits for a lock.
- A co-located Store shares the database’s connection manager and coordinator. Its commit writes inside the Segment’s transaction. A Store write takes the write lock at its call, as
changedoes, and fails withstore busy, withkey, while another Segment holds it.
The http factory
Section titled “The http factory”A Host that offers the optional http calls HTTPCapability in Go or httpCapability in TS, with an implementation and the cost map (ADR 0124, ADR 0151). The Core checks the arguments, invalid serve, invalid response, invalid request and out of domain, and the results. The implementation listens, matches, delivers and answers, and makes requests.
- Operation subsets: an implementation supplies
serve,unserveandrespondtogether,fetch, or all four. Only the Operations it supplies are declared, so a Script that calls another fails to load. Supplying none, or only some of the server three, isinvalid value. - The binding is the Host’s own description of the addresses the Grant may listen on and the origins it may fetch from. The Core never reads it. A binding that allows fetching says so explicitly: an embedded Host’s Grant fetches from no origin unless its binding gives a list of origins, each an exact scheme, host and port, or allows any. An empty list allows none, and a binding the Host can’t read fails when the Host sets up the Grant. The binding also sets the header and body bounds, which default to chapter 7’s.
- The implementation receives
serve’s effective message (httpRequestfor omitted or Nothing) and an omittedoptionsas an empty map. The Trace keeps the call as the Script wrote it, as for a store watch. - Answering:
servestarts a suspending call, answered with{host, port}once the listener listens, or failed withaddress in useorbad address.unserveandrespondare immediate. fetch’s implementation receives the normalized URL as text, withqueryadded, and the request map withoutquery:methodalways present,headersas given,bodyas given, andjsonas its compact JSON text, asrespond’s does. It adds the defaultcontent-typeandaccept-encoding, checks the origin against the binding, and answers with{status, headers, body}or fails withbad address,network errororresponse too large. When the call is abandoned it aborts the request as far as it can. The Trace keeps the call as the Script wrote it.- A JavaScript
fetch()isn’t a conforming implementation on its own: it decompresses content, follows redirects unless told not to, and in a browser hides headers. An implementation uses a lower-level client where it must. A browser Host may leavefetchout. not owner: the implementation compares theCall’s delivery id with the one it Delivered the HTTP Exchange under, and failsrespondwithnot ownerwhen they differ or theCallhas none.- Result checks: a
serveanswer that isn’t a map of texthostand whole-numberportends the call ashost error, and so does afetchanswer that breaks chapter 7’s response rules.
The HTTP router
Section titled “The HTTP router”The Host component that holds Serve Registrations, listens and turns HTTP requests into Deliveries. Its obligations are normative for every Host that offers http:
- Delivery: each HTTP Exchange is one
Script.Deliverto the owning Script, with the argument chapter 7 gives. The router keeps its delivery id until the exchange is answered. - Settling from reports: after each Pump of the Group, the router reads the reports in order. A
run startedfor an exchange’s delivery names its Run. Arun endfor that Run that leaves the exchange unanswered answers it: 404 forunhandled, 503 forcancelledordropped, and 500 otherwise. A Delivery that endsunhandledwithout a Run, or arun discarded, answers 404 or 500 likewise. As a backstop, an exchange whose causal work reports no live Runs and no queued messages is answered 500. - Refusal: a Delivery refused as
MailboxFullis answered 503 at once. A Delivery refused for any other reason removes the registration, as the notification router removes a watch. - Closing: when a client goes, the router marks the exchange closed, so
closedreadstrueandrespondfails withexchange closed. It never cancels the Run. - Saving: a Host doesn’t save a Group with an open exchange. A Group the Host discards has its registrations removed and its open exchanges answered 503.
The peer factory
Section titled “The peer factory”A Host that offers the optional peer calls PeerCapability in Go or peerCapability in TS, with an implementation and the cost map (ADR 0153, ADR 0154, ADR 0155). The Core checks the arguments, raising out of domain, wrong kind, bad message name and not encodable, that reach and expose answer with a Host Object of kind peer, and that caller answers with data, or the call ends as host error. The implementation resolves names, carries Remote Sends and their replies, and delivers what arrives.
- The binding is the Host’s own description of the names the Grant may
reachandexpose, how each resolves, and how each destination is authenticated. The Core never reads it. - One Grant:
Loadrefuses a Script given two Grants whose Capability ispeer, asinvalid value. - The kind
peeris defined by the Core, with no properties. The implementation makes each Peer withgroup.Object("peer", id, native)in the Group that will hold it, and an id it can map back to an exposure, including after a Restore. It makes at most one Peer per exposure in a Group, and gives the existing one again. - Answering:
exposeandreachstart suspending calls.reachis answered with the Peer, or failed withbad addressornot exposed;exposewith the Peer for the exposure, or failed withbad addressorname in use.exposehears its name, or none for an unnamed exposure.unexposehears a name or a Peer.unexposeandcallerare immediate, andpostfire-and-forget. postandcallhear the Peer, the Selector as text and the arguments as a list, which may hold Peers, each from the sending Script’s Grant. The implementation never checks the Peer against that Grant’s binding, since holding it is authority. It answerscallwith the receiver’s reply, or fails it withsend failedand{reason, error}.- Release: the implementation hears its Grants’ releases (the Grant release hook) through
releasein TS and aRelease(GrantContext)method in Go, and its Peer Router withdraws Peer Exposures by them. callergives the Caller Identity the implementation recorded forcall.deliverywhen it gave a Remote Send to the Exposed Script, or Nothing when the call has nodeliveryor the Delivery wasn’t a Remote Send (ADR 0125). When acallis abandoned the implementation drops its reply when it comes; it never asks the receiver to stop.
The peer router
Section titled “The peer router”The Peer Router is the Host component that holds Peer Exposures and carries Remote Sends. Its obligations are normative for every Host that offers peer:
- Lifetime: the router keeps chapter 7’s Lifetime itself; the Core keeps no record of Peer Exposures (ADR 0181). A release with reason
stop,revokeordisablewithdraws every Peer Exposure, named and unnamed, that the released owner’s named Grant made, before the hook returns. A release with reasonreloadkeeps them. Withdrawing one is asunexposedoes: a Remote Send already delivered is unaffected, a latercallfails withnot exposedand a laterpostis dropped. Every Host’s router must pass the peer kit. A Group the Host discards has its Peer Exposures withdrawn the same way.@northtalk/ts/peerin TS andnorthtalk.org/go/peerin Go supply one. - Delivery: a
postthat arrives is oneScript.Deliverto the Exposed Script, and acalloneScript.Request, each under the Selector and arguments sent, with no limit override. A Remote Send that comes after its exposure is withdrawn isnot exposed. - Caller Identity: the router records, against the delivery id of each Remote Send it gives an Exposed Script, what the receiving Host vouches for about the sender: the Host or connection it authenticated, never a claim in the arguments. It keeps the record while the Run lives, across a Save and Restore included. It never names the Script that handed the sender a Peer.
- At most once: the router never delivers a Remote Send twice, retrying a transport included. When it can’t tell whether a
callarrived, it fails it withunreachable. - Replies: a
Requestthat settles answers thecallwith its result. One that rejects withsend failedfails thecallwith the samereasonanderror. AScript.Requestrefused asMailboxFullfails it withreasonmailbox full, and any other refusal, or a reply that can’t be carried back, withunreachable. - Values: arguments and replies cross as the Value Encoding, read against the receiving Group. Each Peer in them crosses as its exposure, and the router gives the receiving Group that exposure’s Peer. They hold no other Host Objects or Function Values, since the Core refuses them at the
sendand a Run’s result that holds one fails thecallwithunreachableand acall failedreport on the receiving side. - Unforgeable Peers: a Peer that crosses between Hosts names its exposure with a secret of at least 128 random bits, and identifies the key of the Host that holds it, so that no one can guess one into existence or redirect one. The router checks that key on every Remote Send to it.
- Saving: a Group may be saved with
calls pending and with Runs that owe a remote reply. The router settles each restored pendingcallwith Fail,send failedandreasonunreachable, and drops the reply of each restored Run that owed one. A Group the Host discards has its exposures removed. Restored exposures, named and unnamed, keep their identity.
The user factory
Section titled “The user factory”A Host that offers the optional user calls UserCapability in Go or userCapability in TS, with an implementation and the cost map (ADR 0077). The Core checks the arguments and each answer, and the implementation shows the prompt and answers it.
- The binding is ignored, as
console’s is. - The implementation receives
messageand eachitemsentry as text,multipleas a boolean, and an omittedprompt,defaultortitleas empty text. A Nothing option is an omitted one, since eachoptionskey is optional. - Answering:
confirm,chooseandenterstart a suspending call, which the implementation answers withAnswerorFail.notifyis fire-and-forget. user busy: the implementation fails aconfirm,chooseorenterwithuser busywhile the same Script has another one it hasn’t answered. It reads the Script from theCall, and a call stops being pending when it is answered, failed or abandoned.- Checking the answer: an answer that breaks the Operation’s result Shape (a boolean for
confirm, text or Nothing forenter, and Nothing, text or a list of texts forchoose) ends the call ashost error. So does achooseanswer that isn’t an item, a text answer undermultiple: true, a list answer without it, and a list that isn’t a subsequence ofitems. Thecall failedreport carries the detail, as for any result that breaks its Shape.
Host Objects
Section titled “Host Objects”An Object Kind may also declare an ordered, named Object Collection, which
element s of o and the number of elements of o read through its Count,
At and Find callbacks (the object element contract).
- Object Kinds are defined once per process, each with its properties. A property has a Shape, a
Getand optionally aSet, each with a cost, and runs inside the Run like an immediate Operation: a value read is checked against the Shape and its conversion charged, and a failure raises as an Operation’s does, withcapabilitythe Object Kind’s name andoperationthe property’s. A value set that breaks the Shape raiseswrong kindbefore theSetruns. A property with noSetis read-only (chapter 4). Asetbelow a property, such asset the isLocked of the door of me to true, calls the property’sGetand then itsSet, each charged and traced as on its own; only theSet’s value is checked against the Shape as a value set. - Handles:
group.Object(kind, id, native)makes a handle the first time a Host-owned thing crosses into the Group. The id is the Host’s, stable, and unique within its kind in the Group (ADR 0008), and a reused one isduplicate object id. An optionalparentgives the new object its parent at once, even inside a Pump, so a Script that gets the object from a Host function and sends to it in the same Run reaches the parent’s Owning Script. The parent must be one of the Group’s handles, orwrong group, and not disposed, orinvalid value. A refused call makes no object. Making an object with a parent writes anobjectrecord to the Trace (ADR 0152).group.ObjectByID(kind, id)returns the handle with that Object Kind name and id, disposed or not, or none if the Group never made one. It is how a Host reaches the handles a Restore made, and it fitsDecodeValue’s resolver (ADR 0058). The Core holds the kind and id, so a Script reads them withobjectKind(o)andthe id of owithout calling the Host (chapter 7). - Parents: the Core holds each object’s parent, and the Host gives it when making the object or changes it with
SetParent, queued as a Host Input. A cycle isparent cycle; changing a disposed child’s parent isinvalid value. Both checks run at admission and again at drain, against the state left by earlier queued inputs and Restore. A refusal known at admission is a Host error at the call. A change that becomes invalid while queued leaves the parent unchanged, writesrefused, and adds a Host-error report to that Pump (*HostErrorin Go;{kind: "host error", code, detail?}in TS). The Pump continues draining later inputs. Parity covers the code; detail is Host-only and outside parity (ADR 0016, chapter 5). - Disposing an object is a queued Host Input. The object stays an ordinary value, with its id and its equality. Sending to it, or reading or setting a property of it, raises
object gone, and disposing an owner stops its Owning Script within the same Host Input. - Well-known objects are bound to names at load, and an Owning Script to its object.
Loading and Libraries
Section titled “Loading and Libraries”Loadcompiles a Script, checks it against its Grants, Libraries and well-known objects, runs its initialiser and adds it to the Group. A rejected Script is aLoadError, with its diagnostics (chapter 2).- Inline source in TS: the
talktemplate tag dedents source written in Host code. It reads the raw template, so NorthTalk’s escapes reach the lexer, and only\`and\$lose their backslash; NorthTalk interpolation is written\${…}. It strips the longest exactly matching whitespace prefix of the non-blank lines, never expanding tabs, so fenced text margins survive. Any JS interpolation throws, so values reach a Script as arguments, never as source. - Script naming: the Host chooses a Script’s name; it need not be a language Name. Colons, dots and slashes are allowed, as in
page:page1andelement:page.one/button:primary. Loading, linking, Reload and Extend preserve the whole name; punctuation in it does not name a Library or an imported definition. - Libraries:
CompileLibrary(src, imports, declarations)checks Capability calls against explicit Operation modes and argument Shapes, and compiles one once per process, andAddLibraryandReplaceLibraryadd it to a Group (chapter 7).ReplaceLibraryalso recompiles every Library that imports the replaced one, and a Host reads the recompiled ones withLibraries. - Reload and extend change a loaded Script’s code (chapter 10).
- Stop ends a Script: its running, parked and suspended Runs are discarded with no
finally, and messages left in its mailbox are dropped (chapter 6). - Forbidding suspension: with
forbidSuspension, a Script must hold no possible Suspension Point: not in its own code, and not reached through a Handler it calls, imported ones included. Each one, or the call through which one is reached, is the load errorcan't suspend here. The option is off by default. Reload, Extend, Library replacement and restore keep it, so new code can’t bring a Suspension Point in, and a Library replacement that would is refused as a whole (ADR 0178). A Host whose Scripts must answer within one Pump, such as one that keeps every wait in its own storage, sets it. - Limits are set per Script at load, and some can be tightened per Delivery (chapter 6). In Go, a nonzero
LimitOverridefield always overrides; a zero field overrides only when its corresponding bit is marked inSet(for example,Set: OverrideFuelPerRunwithFuelPerRun: 0). This preserves omitted numeric fields while allowing an explicit zero budget.
Capability Scopes and Segment-bound effects
Section titled “Capability Scopes and Segment-bound effects”The lifecycle contract specifies declaration validation, Run/Grant ownership, automatic abandonment, participant hooks, failure handling, suspension guards and examples. Its rules apply to every Host interface, including the Message Layer. Lifecycle declarations are normative; executable Core support is separate implementation work.
Ordinary immediate effects remain final. A scope guarantees an abandonment attempt for a still-open resource; it does not undo an explicit close or commit. Segment-bound Operations instead enroll their Grants in the Segment’s one participant, a Segment Coordinator, and defer their effects until the Segment’s outcome is known. No Script syntax is added.
Deliveries
Section titled “Deliveries”- Selectors: a message name that contains
:is a Selector: two or more Names, each followed by:, whose labels are Argument Label words (move:to:), with one argument per part. A Delivery, Request, Broadcast or Decision whose name contains:but isn’t such a Selector, or doesn’t have one argument per part, is refused at the call asinvalid value(ADR 0055). Deliverroutes a message to an object’s Owning Script, or the nearest ancestor that has one, andScript.Deliveraddresses a Script directly (chapter 5). Each returns a delivery id, which the Run it starts reports.Requestis asend … and waitfrom outside. Its future settles with the Run’s result, or rejects withsend failed, itsreason, and for anerroredRun itserror. Cancelling its context or signal queuescancel-delivery. TS’sScript.invoke(name, ...args)is a Request that returns only its result promise, with no delivery id or signal. It is notCall, which calls a Function Value.Broadcastreaches every Script that wants the message when the queue is drained. Each recipient’srun endcarries its own delivery id and the broadcast id.Callcalls a Function Value (Function Values), andDecideasks for a Verdict (Decisions).- Broadcast limit overrides: a Broadcast or Broadcast Decision’s override is checked at the call against the Core’s default limits. Each recipient runs with the tighter of its own limit and the override, so the Broadcast never loosens a recipient’s limits, including a Script loaded after the call.
- Full mailboxes: a Delivery fails at the call with
MailboxFull, which is load shedding, not a Host error, when the messages in its receiver’s mailbox and the Deliveries already queued to that Script fill its mailbox depth. The receiver is the one the Delivery routes to at the call. A Delivery accepted at the call always joins its mailbox when the queue is drained, even past the depth, since a Broadcast’s recipients, aSetParentqueued ahead of it, or the sends of a running Pump for a call made inside one, aren’t known at the call. So a Delivery the Host was told is accepted is never lost.
The Pump and the Group Fingerprint
Section titled “The Pump and the Group Fingerprint”Pump(now, options)takes the Group’s one Clock reading, drains the input queue, fires due waits and runs Runs until nothing is runnable or a Fuel Slice or the Group’s Fuel cap is spent (chapter 5). It returns the Group’s state (idle, sliced, stopped or rewound), the next deadline, the Fuel used and the reports, and the Group is Quiescent.- Deadline range: pending waits retain their mathematical deadlines even outside the Clock’s Instant range. Inspect omits
untilfor such a deadline. The next deadline omits an unreachable future deadline, and uses the current Pump’s Clock reading for an already-due deadline before the Clock range (Waiting). - Code identity: the SHA-256 of the UTF-8 text made of these lines, each ended by LF:
odgn-talk code identity 1, the language version, the Cost Model version,scriptorlibrary, the unit’s name, then the lowercase hexadecimal identity of each Library it imports directly, one per line, each once, in the order of the firstuseline that names it, then a linesourcefollowed by the source exactly as given. An imported Library’s identity covers its own imports, so a unit’s identity covers every Library it reaches (chapter 7). A source that doesn’t parse names no imports, and auseline that names a Library the Group doesn’t hold adds none, so aloadthat fails still has an identity. An extension’s identity is in chapter 10. - The Group Fingerprint is the SHA-256 of the UTF-8 JSON, with no white space, keys in the order given here, strings escaping only
",\and U+0000 to U+001F (as\",\\and lowercase\u00xx), and numbers as JSON integers, of{"language", "costModel", "libraries", "scripts"}:librariesis each Library the Host added, as[name, identity], ordered by name. The stdlib Libraries aren’t listed, since the language version fixes them.scriptsis each Script’s{"name", "identity", "grants", "limits"}, followed by"forbidSuspension": trueonly for a Script loaded with it, ordered by name.grantsmaps each granted name to its Capability’s name and its Operation Declarations, in the Host Manifest’s data model, ordered by name. A Grant counts whether or not it is revoked or disabled, and one a restore couldn’t re-bind counts with its saved Capability and declarations, since revoking is state (chapter 10).limitsmaps each limit’stsname inlimits.tomlto the value the Script has after defaults, durations in whole milliseconds, ordered as inlimits.toml.- Each granted name maps to
{"capability", "operations"}. Operations are ordered by name, with keysname,mode,args, optionallabels, optionalresult,cost, optionalmaxPending, optionalerrors, optionalscope, optionalsegmentBound, optionalcommand, optionalmetering, in that order. Missingargsis[];costhasfuel, thenalloc, with missing allocation written as0.maxPendingis whole milliseconds and appears only when declared on a suspending Operation. A scope writes{"opens", "abandon"}or{"closes"}in that key order;segmentBoundandcommandappear only astrue, with absent and false equivalent, andlabelsonly when it isn’t empty. Bindings, Host functions, lifecycle hooks,descriptionandexamplesare excluded. Omittederrorsstays omitted, while an explicit empty catalogue is[], since these accept different failures. Errors are ordered by code, each as{"code", "fields"}; missing fields is[], and fields retain declaration order. - A scalar Shape is its kind name, or
"any"or"value". The wrappers are{"quantity": unit},{"unitKind": kind},{"object": kind},{"list": shape},{"oneOf": [shape, …]}and{"optional": shape}. Theobjectwrapper names an Object Kind. A map Shape is{"map": [field, …]}, followed by"open": trueonly for an open map. Each field, including an error field, haskey,shape, thenoptional: trueonly if optional; fields and alternatives retain declaration order. These are the Host Manifest’s data model with explicit canonical ordering and defaults. - Identities are lowercase hexadecimal. The Fingerprint never covers state, so two Groups in lockstep compare it once, before they start.
Inspect()exposes each Script’s disabled named Grants indisabledGrants, sorted in Unicode code-point order and omitted when empty, andforbidSuspension: truefor a Script loaded with it, omitted otherwise. It reads the Group without changing it, between Pumps: each Script’s Script Variables in declaration order, its Runs that haven’t ended, with their status, Handler and what each suspended one waits for, and the messages in its mailbox. A suspended Run’swaitanduntilare the end reason and deadline itssegrecord wrote, so a call’smaxPendingorMaxWaitgives nountil, and itscallsare the call ids, reply ids or Join Members it still waits for. It charges nothing, and is the Host Inputvarsin the Trace (chapter 11). A REPL’s:vars,:runsand:mailboxrender it (chapter 12).
Script counters
Section titled “Script counters”Script.Counters() is a worker read between Pumps. It returns a fresh snapshot, charges nothing, drains no Host Inputs and changes no scheduling state. It is the Host Input counters <script> in the Trace, followed by one counters output record (chapter 11).
FuelTotal,AllocTotal: all Fuel and allocation charged to the Script’s Runs since load, including live Runs, event Pattern/Guard tests, Capability Charges, Reissue and Script cancellation cleanup. Automatic scope abandonment and Segment lifecycle hooks charge neither Fuel nor allocation. Initialisers at Load, Reload and Extend contribute nothing. A refused Charge or inactive asynchronous request contributes nothing; accepted asynchronous charges count in their admission Pump even without a Segment. Rollback, Stop, Reload, Library replacement and either restore policy retain already charged work; a live Run’s work is counted once when it ends or is discarded.Runs: Runs started since load, including a Run that parks, drops, is unhandled, errors, faults or is cancelled. Each Handler dispatch or Function Value call that starts a Run increments it once; event tests are part of the waiting Run. A Delivery cancelled before dispatch, a stale Function call, a Message Path transfer or an unhandled path with no Owning Script starts no Run. An internalerrormessage with no Handler starts no Run either.Faults: Runs that ended with the outcomelimit fault, once per Run. Ordinary errors, effect failures, Stop and cancellation do not increment it; a Cleanup Budget failure still endscancelled.PersistentState: current logical Persistent State in bytes, with the same accounting as the Script’s cap (chapter 6). It includes Script Variables, retained Runs and mailbox messages, and falls when work is released.MailboxLen: messages currently in the Script’s mailbox. It excludes preempted, ready, suspended and parked Runs and Host Inputs not yet drained. A message’s transfer changes the readouts only when a Pump transfers it.
The four lifetime counters carry over Reload, Extend, Library replacement and full or variables-only restore. The two current-state readouts describe the resulting state, rather than preserving the old mailbox or discarded Runs (chapter 10).
Function Values
Section titled “Function Values”- What the Host holds: a Function Value is an ordinary
Valueof kindfunction. The Host can read only its Home Script and its display form, and it can’t build one. - Bound to its Group: passing it into another Group is
wrong group, including inside lists, maps and Function captures. Host message inputs, Call answers/failures and restored settlements refuse these values before accepting them. An immediate or automatically forwarded Promise result, property result or raised Capability failure containing such a value giveshost error, like an invalid result or failure. This also applies when a restored Operation is reissued. It lives as long as the Host holds it, and nothing needs releasing. - Calling it:
group.Callhas the shape ofRequest. It is a Delivery to the Home Script, recorded in the Trace as acall-valueHost Input (chapter 11). - Staleness: checked when the queue is drained. A stale value rejects with
send failed, reasonfunction gone, and nothing runs. - Argument count: a live Host call starts a Run without a Handler Clause. Before entering its body, the Run checks the Function Value’s arity. A mismatch ends it
erroredwithwrong arityat the body’s first instruction, without executing or charging that instruction or unwinding a frame; the function’scatchandfinallyregions do not apply. The Request rejects withsend failed, reasonerrored. Defaults and captures are bound in the value’s own code unit. - Inspection: a pending Function Value call uses its display form as the mailbox Message’s
name; its Run’shandlerreadout uses the same display form. These are inspection labels, not Handler dispatch names. - Taking one as an argument: an Operation that accepts a Function Value declares the
functionShape, orvaluewhen it accepts all values. Lists and maps can declare fields or items with these Shapes too. - Not durable: Host storage can’t encode it, and a Host-held handle doesn’t survive save and restore. Only the message layer carries it, as a reference form (below). A callback that must survive a save should be an ordinary message, as the
timerCapability’s are.
Decisions
Section titled “Decisions”A Decision asks Scripts whether something may happen, such as a game move or a form submit, and gets back a Verdict (ADR 0031, #80).
- The calls:
group.Decide(ctx, to, m),script.Decide(ctx, m)andgroup.DecideBroadcast(ctx, m)are queued, likeRequest. They return an id and aDecidingfuture that settles with aDecided. - The Verdict:
allowed,vetoedorundecided.Decidedalso lists every veto as{script, run, reason}, in recipient order, and every undecided recipient as{script, run, outcome}. - When it settles: at the end of the first Segment of the first
, decidingRun that the Decision reaches. The Pump that seals it returns adecidedreport. Usually that is the Pump that drains it. Behind a Fuel Slice or a mailbox backlog it takes more, and a Host that must know now pumps again at the same Clock reading. - Undecided means the deciding Run errored, hit a Limit Fault, ended
effect failed, was cancelled, dropped or stopped before it sealed. The Core never guesses allow or refuse, so the Host chooses. - Deadlines are the Host’s: cancelling the context or signal before the seal queues
cancel-delivery, and the Decision settles as undecided,cancelled. Cancelling after the seal does nothing, sodefer cancel()is safe. - Broadcast: it settles once every recipient has sealed. It is vetoed if any recipient vetoed, undecided if none did but one was undecided, and allowed otherwise, including when there are no recipients.
- Reports alongside it: the deciding Run still gets its own
run end, often later than thedecidedreport, since an allowed Run may go on. A Decision that reaches the end of its Message Path is allowed, andunhandledis reported as usual. - Not durable: like
Pending, the future doesn’t survive a restore. Thedecidedreport still arrives with the same id.
The message layer
Section titled “The message layer”The message layer is the language-neutral form of this interface, for Hosts over WASI or a sidecar process, including language-specific embedding adapters and Hosts such as Elixir (ADR 0030, #79). The message-layer research gives the reasons and the measurements.
- One message per call: each call in
talk.gois one JSON message with a reply, or a negotiated binary frame.request-pump-fields-v1carries Request, Function call and Pump exchanges, including explicit combined admission/Pump worker calls;binary-frames-v1is the older all-binary contract. Values use the Value Encoding, and declarations and Shapes use the Host Manifest’s data model. - Combined admission and Pump:
RequestPumpandCallPump(TS:requestPumpandcallPump; Elixir:request_pumpandcall_pump) claim the worker, admit exactly once and perform one ordinary Pump. Admission refusal returns no delivery or Pending and does not Pump. Pump refusal retains the admitted handles and leaves the input queued. Earlier inputs keep their order; the Pending may remain unsettled. TS returns a structuredPumpedRequestdistinguishing admission failure from Pump failure with the retainedrequestedhandle. Elixir returns aNorthTalk.Pumpedholding aNorthTalk.Pendinghandle and the Pump outcome. The binary exchange contract defines readiness, correlation, cancellation and negotiation. Unsupported guests refuse before admission without a two-call fallback. - Nesting: frames and their Value Encodings have no fixed nesting-depth limit. A valid deeply nested frame is decoded and dispatched normally, subject to available memory and the transport’s frame-size limit; nesting alone is not a protocol error. This holds on native and WASI builds alike (ADR 0088). This applies to incoming Values, ignored fields, and Values in replies and interim needs. A malformed frame, including malformed deep JSON, is still a protocol error and leaves the Session and any pending Host exchange available for a corrected frame. Hosts must choose a JSON decoder that can read deep replies within their own resources.
- The Host starts every exchange: Host code runs through interim replies: Operations, properties and lifecycle hooks reply to
pump; scope abandonment and rollback may also reply toreloadorreplace-library, and the Host answers it before another worker exchange. While a need remains open, paused crossing inputs may be admitted to the same Group under separate refs, without resuming execution. Interim requests belong to that Host-started exchange. The opt-in inline transport carries nested observation and admission frames through WASI stdio while the worker stack remains active; it never reenters a guest export. With the opt-ingroup-exchanges-v1, an open need holds up only its own Group’s exchange. With the opt-inbinary-frames-v1, every frame afterhellois binary. - Received means read: a queued call is received when the Core reads it, including a permitted input sent while a callback need is outstanding. Its delivery id is assigned then, and
mailbox fullis decided then. A binding preserving synchronous callback admission must submit it then, rather than defer it in an outbox until the worker finishes. - Stops land at a crossing:
stop,cancel-runandrewind-runland at the latest at the running Pump’s nextoporprop, or at its end. The Trace records where. - Restore bindings:
restore-bindings-v1advertises registration of Capability declarations and Grants while aresolveneed is open. Those registration exchanges use refs distinct from the restore’s;resolve-resultkeeps the restore ref. Other exchanges remain blocked. The successful restore reply also includesscriptsin load order,objectsas all retained[kind, id]identities (including disposed ones), and each pending Call’scapability,run,segmentandnow, so an adapter can rebuild public handles and Call accessors before exposing the reply or its Trace. The save bytes remain opaque, in chapter 10’s save format. - Abandoned calls: the
abandonedfield of a final successfulpump,reloadorreplace-libraryreply lists, in call id order, the suspending calls the Host answeredstartedthat the Core has abandoned since its previous notification: by a timeout, a cancelled, stopped or rewound Run, a failed Join Member’s siblings, or a lost restore. It stands in for the context or signal an in-process Host’sCallgives: the Host stops the call’s work and drops its queuedanswerorfail. One sent anyway is a late answer, recorded and ignored. A Host opting intoabandoned-before-needs-v1receives these notices at the outer level of interim needs and final worker errors as well, before invoking the next callback; each is listed once across the worker’s replies. Without opt-in, existing final-success-reply timing is preserved. - Charging: each
opcarries the Fuel the Run has left after the declared cost. The Host’sChargesubtracts from it locally and fails exactly when it would go below 0, and its reply carries the total acceptedcharged. Refusal is latched and uses alimitreply even after earlier increments succeeded. Afterstarted, localfuelLeftis no longer authorization: asynchronous metering usesrequest-chargeand a later Pump outcome. - Ids are the Core’s: delivery ids, run ids and call ids are assigned as chapter 11 says. Handles for Grants, Libraries (by identity), Groups and Scripts (by name), and Host Objects (
[kind, id]) are the Host’s. - Host Objects cross as
{"$object": [kind, id]}, read against the message’s Group. The Host’s glue code raiseswrong groupbefore it sends another Group’s object. - Function Values cross as
{"$function": [home, display, token]}. Withfunction-metadata-v1, Core-to-Host values instead use{"$function": [home, display, token, name, required, total, unit]}:unitis the defining code unit’s 32-byte identity as a Value Encoding byte string,nameis the declared name, ornullfor a Lambda, andrequiredandtotalare nonnegative integer parameter counts, withrequired <= total. These describe the value’s defining code even after it becomes stale or is saved and restored. Without opt-in the three-item form is unchanged. Hosts may return the three-item form, the six-item form withoutunit, or the full seven-item form; metadata is descriptive and never overrides the Function identified by the token. The token is opaque, and holds the value’s own data and its Group, so nothing needs releasing. Opting into metadata changes neither the token nor Function identity, including for captured Function Values. The Core checkswrong groupwhen it reads a token, andfunction gonewhen the queue is drained. A token belongs to the Group instance that wrote it: a restored Group, even one restored under the same handle afterdrop-group, is a new instance, and reading an earlier instance’s token iswrong group, as an in-process Host’s Function Value from before a restore belongs to the old Group. Host storage refuses every form of the tag. A Session Host retains defining-source versions byunit, usingscript-unitsbefore code changes can discard them, so stale Function Values still find their original Declaration Documentation. - Core-raised error maps cross as plain maps. With
core-message-v1, a map whosemessagethe Core wrote (chapter 6) instead crosses as{"$coreError": [[key, value], …]}, in order, whatever its keys, so a Host that renders the Trace can leave thatmessageout as the Core does. Arun end’serroris its own field, not a Value Encoding, and stays a plain map. A Host may send the tag back; the Core then reads the map as Core-raised. One without a textmessageisinvalid value, and so is the tag without opt-in. Host storage refuses it. - Never crossing: Grant bindings, native objects,
OnReadyand futures stay on the Host’s side.
Messages
Section titled “Messages”A message is {"m": <name>, "ref": <n>, …fields}, where ref is the Host’s integer, which the reply echoes. A reply is {"ref": n, "ok": {…}} or {"ref": n, "err": {…}}. The error forms are {"kind": "host error", "code", "detail"}, {"kind": "load error", "diagnostics": [{code, message, unit, line, col, endLine, endCol}]} and {"kind": "mailbox full"}. A reply to pump, restore, reload or replace-library may be {"ref": n, "need": {…}} instead, which the Host answers with the matching …-result message under the same ref. Every Group message has a group field, and every Script message a script field too. (V) marks a field in the Value Encoding.
| Message | Fields | Reply | talk.go |
|---|---|---|---|
hello |
protocol, optional features: requested supported feature names |
language, costModel, unicode, core, saveFormat, optional features: text names (paused-inputs-v1 advertises paused-input admission; abandoned-before-needs-v1 supports opt-in cancellation before callbacks; crossing-trace-v1 supports opt-in Operation Trace observation before landing; climb-v1 supports opt-in climbed on run end reports; function-gone-v1 supports opt-in gone on Pump replies; function-metadata-v1 adds defining names, arities and source identities to Function Values and opens script-units; core-message-v1 marks Core-raised error maps as $coreError; inline-inputs-v1 supports synchronous per-record observation and admission during exports; chunked-wasi-v1 supports bounded WASI chunks for large logical messages; restore-bindings-v1 supports binding registration during resolution and restored Host handle metadata; queued-inputs-v1 opens Trace-silent pending Host Input queries; analysis-v1 opens the language analysis messages; session-v1 serves a Session Host on the guest; group-exchanges-v1 gives each Group its own exchange and opens drop-group; binary-frames-v1 makes every later frame binary; request-pump-fields-v1 selects the binary Request/Pump exchange, mutually exclusive with binary-frames-v1) |
CoreVersions |
define-capability |
name, optional handle: a distinct transport identity used by grant and Operation needs while declarations and Fingerprints keep name; ops: Operation Declarations, each with optional description and examples, optional segmentLifecycle: true advertising all three hooks, optional release: true advertising the Grant release hook; optional standard refinement family with standard-refinements-v1; optional musicalClock: true for the musical clock, whose fixed declaration the Core supplies |
– | DefineCapability, DefineSegmentCapability, DefineCoordinatedCapability, MusicalClockCapability |
standard-capability |
name, costs; for store, the Host answers effect requests as its lifecycle hooks and release requests as its Grant release hook. sqlite isn’t offered through the message layer yet |
– | ClockCapability and the others |
add |
a (V), b (V) |
value (V), or fail: {code, message, data (V)} |
Add |
explain |
value (V), shape: a Shape in the Host Manifest’s data spelling, optional group to read value’s Host Objects and Function Values against |
value (V): the explain Built-in’s report; pure, uncharged, no Trace |
Conforms, Explain |
define-object-kind |
name, props: [{name, shape, readOnly, getCost, setCost}], parentKinds, and with object-elements-v1 an optional elements: {shape, countCost, atCost, findCost} |
– | DefineObjectKind |
grant |
capability, ops: names, or "all", optional coordinator: the name of its Segment Coordinator, shared by every Grant given that name; optional locale default tag or maxRows sqlite row cap with standard-refinements-v1 |
grant: a handle |
Grant, GrantAll |
compile-library |
name, version, source, imports: identities, declarations: Operation modes, argument Shapes and any labels |
identity, needs |
CompileLibrary |
new-group |
name, trace: a boolean, optional seed: an integer from 0 to 2^64 − 1, in the integer encoding |
– | NewGroup |
drop-group (group-exchanges-v1) |
– | – | the Host letting go of a Group (dropping a Group) |
load |
name, source, grants: {name: handle}, grantsAsUsed, optional forbidSuspension, owner, objects, limits |
script, trace |
Load |
add-library, replace-library |
identity, and carry and optional keepMailbox for a replace |
–, or reports and abandoned |
AddLibrary, ReplaceLibrary |
libraries |
– | libraries: [{name, identity}], in the order the Group added them; reads the Group without changing it, with no Trace line |
Libraries |
object |
kind, id, optional parent |
– | Object |
set-parent, dispose |
object, and parent |
– | SetParent, Dispose |
deliver, request |
to: {object} or {script}, message: {name, args (V), limits} |
delivery |
Deliver, Request |
cancel-delivery |
delivery |
– | cancelling a Request, Decide or Call |
broadcast |
message |
broadcast |
Broadcast |
call |
fn (V), args (V), limits |
delivery |
Call |
decide |
to, message, or broadcast: true and message for a Broadcast Decision |
delivery, or broadcast |
Decide, DecideBroadcast |
answer |
call, value (V), and optionally fuel |
– | Answer, AnswerWithCost |
fail |
call, error: {code, message, data (V)} |
– | Fail |
pump |
now, fuelSlice, fuelCap |
state, nextDeadline, fuelUsed, reports, abandoned, trace, and gone with function-gone-v1 |
Pump |
request-pump |
token, to, message, now, fuelSlice, fuelCap (negotiated binary only) |
admission refusal, or admitted delivery, token and ordinary Pump outcome, including a Pump error |
Script.RequestPump, Group.RequestPump |
call-pump |
token, fn (V), args (V), limits, now, fuelSlice, fuelCap (negotiated binary only) |
admission refusal, or admitted delivery, token and ordinary Pump outcome, including a Pump error |
Group.CallPump |
cancel-correlated |
token (JSON, after Request/Pump negotiation) |
same as cancel-delivery; token is retired by final combined reply |
cancelling a combined provisional Pending |
request-charge |
call, fuel |
request (enqueue acknowledgment); outcome in a later Pump charge result report |
Call.RequestCharge |
op (interim) |
call, script, run, segment, grant, capability, operation, mode, now, args (V), optional scope, automatic, and fuelLeft for Script calls only |
op-result: {result (V)}, {started}, {done}, {fail}, {limit} or {hostError}, each with charged |
Do, Start, Fire |
trace (interim, crossing-trace-v1) |
outer trace: Operation crossing records before landing; optional settled beside abandoned identifies consumed Calls |
trace-result: no fields |
Trace sink |
effect (interim) |
script, run, segment, grant: the first enrolled, grants: every enrolled Grant name in enrollment order, optional coordinator, phase: begin, commit or rollback, now |
effect-result: {status: "ok" | "failed" | "unknown", detail?} |
Segment lifecycle hooks |
release (interim) |
script, grant, reason: stop, reload, revoke or disable, now |
release-result: no fields |
Grant release hook |
prop (interim) |
object, prop, and value (V) for a set; with object-elements-v1, prop elements with op count, at or find and, for at and find, selector (V) |
prop-result: {value (V)}, {ok}, {fail} or {hostError} |
Get, Set, and an Object Collection’s Count, At and Find |
save, fingerprint |
– | save, fingerprint: bytes |
Save, Fingerprint |
state-fingerprint |
– | stateFingerprint: bytes |
Group.StateFingerprint |
save-state-fingerprint |
save, naming no Group |
stateFingerprint: bytes |
Core.StateFingerprint |
inspect |
– | scripts: [{name, disabledGrants?, forbidSuspension?, vars: [[name, value (V)]], runs: [{id, status, handler, wait?, until?, calls?}], mailbox: [{delivery, from, message}]}] |
Inspect |
restore |
name, save, libraries: identities, mismatch, optional keepMailbox, trace |
variablesOnly, reloaded, pending: [{call, script, grant, operation, args (V)}], disposed: [[kind, id]], discardedRuns, droppedMessages, abandonedCalls, reports |
Restore |
resolve (interim) |
grants: [[script, name]], objects: [[kind, id]] |
resolve-result: grants: handles or null, objects: booleans; with restore-bindings-v1, define-capability and grant may first register bindings under distinct refs, without admitting Group work |
Grants, Resolve |
settle |
call, settlement: {answer (V)}, {fail}, {reissue} or {adopt} |
– | Settle; an adopted call is answered with answer or fail |
reload, extend |
source, and carry and optional keepMailbox for a reload |
reports and abandoned, or – |
Reload, Extend |
stop, cancel-run, rewind-run, revoke |
reason, run, or grant: the name |
– | Stop, CancelRun, RewindRun, Revoke |
counters, grants |
– | Counters, or {name: [ops]} |
Counters, Grants |
export-manifest |
the manifest’s definitions, by handle | manifest: bytes |
ExportManifest |
queued-inputs (queued-inputs-v1) |
– | queued: boolean, whether Host Inputs remain for the Group’s next Pump; reads without execution, a vars snapshot or Trace, between worker exchanges only; excludes runnable Runs and messages already in Script mailboxes |
private Session Host queue observation |
script-units (function-metadata-v1) |
script |
units: [{name, source, identity: bytes}], the Script’s current own and extension units and their transitive Library imports; reads source without execution, a vars snapshot or Trace |
talk_script_unit, extended with imported Libraries |
analyze-entry (analysis-v1) |
source, optional handlers, optional bound: text names |
kind, doc, declarations, implicit, and problem for a syntax error |
– |
analyze-source (analysis-v1) |
source |
declarations, or problem |
– |
analysis-catalogue (analysis-v1) |
– | builtins: [{name, call, gives}], libraries: [{name, source}], inspectReader |
– |
message-name (analysis-v1) |
name, arity |
valid |
– |
session-open (session-v1) |
optional clock: "real" or a virtual Clock’s $instant text; optional limits: {fuelPerRun, allocPerRun, maxWaitMs, maxJoin}; optional objects: envelope texts; optional transcript: a recorded Transcript’s text |
a session reply | – |
session-input (session-v1) |
one of input with optional more: text lines, line, answer: {shown, fail}, or envelope: text; reading under a real Clock |
a session reply, or a prop, resolve or write need |
– |
session-pump (session-v1) |
reading under a real Clock |
a session reply, or a need | – |
session-describe-prompt (session-v1) |
– | call, kind, message, prompt, default, items, multiple |
– |
session-complete (session-v1) |
text: the lines a Driver has collected |
complete: whether they are a whole Entry or Session Command |
– |
session-inspect (session-v1) |
– | inspect’s reply for the session’s Group, beside the session’s records |
– |
session-close (session-v1) |
– | – | – |
- Reports are
talk.ts’sReportunion as data:run end(script,run,delivery,broadcast,handler,fallback,outcome,result (V),error,limit,effect,at,fuel,alloc),stop,unhandled,call failed,effect failure,decided,run started,run discarded,run accountingandcausal work. The latter four use the fields in Run accounting;fnandargscarry Value Encoding values. A Host opting intoclimb-v1also getsclimbed: trueon therun endof a Run whose message went on up the Message Path, bypassor with no clause taking it. That Run hasn’t answered its asker, so the Host keeps theRequestorDecidefuture open until a laterrun end,unhandledordecidedreport settles it. An in-process Core knows this without the field. Withfunction-gone-v1, a Pump reply’sgonelists the delivery ids of HostCalls found stale at the drain, which end with no report: the Host rejects each withsend failed, reasonfunction gone. - Encodings:
nowandnextDeadlineare$instanttext, byte strings (saves, identities, fingerprints) are{"$bytes": …}, durations are whole milliseconds, and every other integer is a JSON integer when its magnitude is below 2⁵³, and its decimal text in a JSON string otherwise. - Traces: when a Group was made with
trace: true, the reply to every message that is a Host Input recorded in the Trace carriestrace, the records it made (chapter 11). The opt-in Operation crossing observation carries available records on interim and error replies, and waits for the sink before landing controls. - Inline admission: an embedding preserving synchronous per-record sinks and concurrent queued calls uses the opt-in inline-inputs contract. Sink-generated inputs follow the ordinary queue and control rules before the record producer continues; inputs arriving during an export share the same admission order.
- Framing: over WASI, the Host writes a frame into a buffer the export
talk_buffer(n)gives, andtalk_send(n)returns the reply’s pointer and length packed asptr << 32 | len. A sidecar sends each frame as a 4-byte big-endian length, then the JSON, both ways on stdio. The opt-inchunked-wasi-v1transport adds chunk exports and inline continuation headers without changing logical messages.
Automatic op requests have automatic: true, no fuelLeft, and a zero charged reply. They take args: [] and use the ordinary immediate op-result; an invalid result is a failed abandonment. Script requests have automatic: false. The Core applies acquisition/closure acknowledgements before processing result conversion or queued interruption. Lifecycle effect-result replies carry no Script values or charges. A release exchange carries the enclosing pump, reload or replace-library ref and waits for release-result; it adds no Trace record or charge. The enclosing worker call returns final reports only after all its interim exchanges complete. A malformed lifecycle reply is unknown, not an ordinary Script error.
standard-refinements-v1 supports adapters whose Standard factory wrappers
resolve defaults and convert Host values themselves. define-capability may
name a standard family (calendar, locale, store, sqlite or user)
independently of the declaration’s handle name. It carries the whole factory’s
Operations and copied costs. The guest applies that family’s precharge checks,
result refinements and permitted catalogue failures, while op needs retain
the supplied Script arguments. Host callbacks perform the factory’s normal
default resolution and, for sqlite, parameter/result conversion and per-step
charging. A Locale Grant carries its effective default tag in locale; a
sqlite Grant carries its row cap in maxRows, independently of its shared
coordinator. These fields copy only the data the guest needs to validate
calls; arbitrary Host bindings stay in the adapter. An ordinary declaration
without standard never acquires factory refinements from its name.
Language analysis
Section titled “Language analysis”analysis-v1 serves a Session Host on the message layer the Core’s own reading of source, so it decides Entries as an in-process Session Host does (#1090). Its messages read only their fields: they load nothing, touch no Group, record no Trace and may be sent before new-group. Without the opt-in each is a protocol error. A missing or malformed field is invalid value.
analyze-entrydecides one Entry.handlersare the first Names of the Session Script’s Handlers, so that a Command Call to one is a statement;boundare the names the Script already has.kindisdeclaration,statement,expression, oremptyfor blank input or a lone--|block.docisattachedwhen a--|block directly precedes the Entry’s first line,pendingwhen nothing has followed the block yet, andnoneotherwise; a blank line after a block detaches it. The Session Host refuses an attached block before anything but a declaration other thanuse.problemis the first syntax error:{code, line, col, endLine, endCol, incomplete, trailing}, positioned in the Entry’s own lines, with its range (chapter 2).incompletemeans more lines could complete the Entry, as a REPL waits for them (Fenced text in sessions and tooling);trailingmeans a whole statement or expression was followed by more input. Load-time diagnostics still come fromload,extendorreload.declarationsare a declaration Entry’s, asanalyze-sourcegives them. An Entry has exactly one;:fixaccepts several.implicitare a statement’s or expression’s implicit Script Variables, in the order first bound, without theboundnames.
analyze-sourcelists a source’s declarations in order, or its first syntax error asproblem. Each is{kind, name, word?, private, span, signature, doc, arity?, initializer?, imports?}:kindishandler,function,constant,variableoruse.nameis a Handler’s Selector orany message, and auseline’s Library;wordis a Handler’s first Name.spanis{start, end, line, endLine}: UTF-8 byte offsets from its first token to the end of its last token before the next declaration, and their 1-based lines.signatureis its head: through the end of a function’s or Handler’s first line, orconstant xandscript variable x.docis the--|block straight before it, each line without its indentation,--|and one space, joined with LF.arityis a function’s[required, total]parameters,initializera Script Variable’s text after=, andimportsauseline’s[{name, local}].
analysis-cataloguegives the Built-in catalogue:describeand:aproposread, the Standard Library’s sources and the normative:inspectreader template.message-namesays whether asendcould computenameforarityarguments: a Name, or a Selector with one part per argument.:traceand:describecheck Selectors with it.
Display formatting of Values (:inspect rows, :describe values, Text forms) stays with the Host. The C API has no counterpart: an in-process Session Host links the Core’s analysis directly, and a C Host that needs it uses the message layer.
Sessions
Section titled “Sessions”session-v1 serves the Core’s own Session Host on the message layer, so a Host keeps only its Session Driver, its I/O and its Host Objects (ADR 0180). One guest serves one session, which owns its Group. Once session-open succeeds, the guest refuses every other message but hello’s and analysis-v1’s, and after session-close it serves no session again. Without the opt-in each message is a protocol error.
-
Opening.
clockstarts the session’s Clock;realis the default.limitsare those:limitssets.objects, present even when empty, means the Host serves live Host Objects: its texts are thekind,objectandsetupenvelopes it declares. Between Host calls, asession-inputenvelopedeclares more, or is a Host action: aninputenvelope with itsrequestalone, which the session performs at once and records with itsreply. Atranscriptreplays through the session first, and records nothing: the reply carries no output, Trace or Transcript Items, and a line the replay doesn’t write the same way refusessession-open, naming the line. A recorded Transcript declares its own objects, soobjectsmust then be empty. -
Readings. Under a real Clock, every
session-inputandsession-pumpcarriesreading, the Clock reading each Pump takes during it and while its needs are answered; under a virtual Clock none may. Each Pump that takes it records an@line. -
Waiting. Nothing sleeps or blocks. A Host call whose foreground waits for a
readline, auserprompt’s answer or a deadline stays open, and the reply says so. Asession-inputlineoranswergoes on with it; asession-pumpPumps at the deadline; any other input ends the wait first, the Run going on in the background, as a Transcript that reads on ends it. With no Host call open, asession-pumpis a Pump at a deadline, as a Transcript’s@line outside any other input. Auserprompt while another waits is answereduser busyat once, and recorded. -
Needs. Three answers are
needs, answered under the asking frame’sref, and each stays open across frames: while one is,session-input,session-pump,session-describe-prompt,session-completeandsession-inspectare refused, andsession-closeabandons it.propis a live crossing, as a Group’s: the Pump waits at its Crossing Pause.prop-resultgives one outcome,value (V),ok,failorhostError, and optionalenvelopes: what the Host did before answering, in order, as declarations of identities its answer names and Host actions. Each is recorded before the crossing’sproperty-end, a refused action with its refusal.resolve, withobjects:[[kind, id]], is a live Restore asking whether each identity still resolves.resolve-resultgivesobjects: booleans.write, withdirectory,nameanddata, is a file:exportor:store savewrites.write-resultgiveswritten: whether it was.
After a
resolveorwriteanswer, the command runs again from its start with every answer it has had, so it asks only for the next. -
Replies. A session reply is
ok:waiting(promptwhen nothing is open,read,user,deadline, orneed),clock(realorvirtual), anddeadline, the next deadline’s$instanttext under a real Clock, ornull. Besideokorneed, every session reply carriesoutput, the lines the session printed;trace, its Group’s Trace lines; andtranscript, its Transcript Items as a Transcript’s lines, in the order the session made them. -
Inputs. An
inputis one Entry or Session Command, with any further lines inmore, as a Transcript’s|lines hold them; a command that names a file carries the file’s lines there instead.session-completetells a Driver collecting lines whethertextis whole yet, as Fenced text in sessions and tooling reads it with the session’s own names, so it knows when to send it.:helpand:quitare the Host’s, and aren’t recorded. -
Inspecting.
session-inspectgivesinspect’s reply for the session’s Group, as a Trace Case ends, and itstraceholds the Group’s snapshot. It is no input, and records nothing::varsis the Session Command a Transcript holds. A Function Value’s token is empty, since no message takes it back. -
Prompts.
session-describe-promptgives the waitinguserprompt: itscall,kind(confirm,chooseorenter), and itsmessage,prompt,default,itemsandmultiple, each empty or false when its Operation has none. Anansweris{shown, fail}: the value in the display form, or withfail: truean error map.
Host error catalogue
Section titled “Host error catalogue”Host misuse known at admission is refused at the call that made it, as a HostError with one of these codes. A queued parent change that becomes invalid is refused at drain and reports through Pump as described under Objects. Parity covers the code, not the detail text.
| Code | Raised when |
|---|---|
clock backwards |
A Pump, or the first Pump after a restore, reads a Clock earlier than the last one |
parent cycle |
setParent would make a cycle |
duplicate object id |
A Host Object id is reused within its kind in one Group |
name reused |
extend Script reuses a name, or a Library name is added twice |
reentrant call |
A worker call is made from inside the Group’s own Pump or a scope/Segment lifecycle callback |
wrong group |
A Function Value or Host Object is passed into a Group it doesn’t belong to |
library mismatch |
A Library’s imports aren’t in the Group, or have different identities there |
reserved name |
A Host registers a Library under a stdlib name |
not adoptable |
A TS run call is settled by adopt after a restore |
invalid value |
Input the value model can’t hold (ADR 0030), a malformed declaration, a message name with a : that isn’t a Selector with one argument per part (ADR 0055), or a limit override that loosens |
invalid save |
Restore is given bytes this Core can’t read: another Core family’s save, a save format it no longer reads, or corrupt bytes |
save mismatch |
A save’s versions, Libraries or Grants don’t match, and the Host’s policy is to reject |
unknown call |
Settle names a call id that isn’t pending or one already settled, or is made once the first Pump has started |
state too large |
The state an extension adds, or the Script Variables a Reload or a variables-only restore carries over, would exceed the Persistent State cap |
effects pending |
Save is attempted while a Capability Scope or Segment participant is live, an asynchronous metered call is pending, a charge request is unresolved, or after fatal effect uncertainty stopped the Group |
effect state unknown |
Load, Reload, Extend or ReplaceLibrary attempts to change a Group stopped by fatal effect uncertainty |
invalid checkpoint |
A checkpoint’s routing state is missing, unreadable or doesn’t match its Group save |
A LoadError carries load-time diagnostics instead, and MailboxFull is load shedding, not a bug.
The Host Manifest format
Section titled “The Host Manifest format”- The file:
ExportManifestwrites one JSON file per kind of Script, named<kind>.talk-manifest.json. The same definitions always give the same bytes. - Its fields:
kind,versionandlanguage, then these arrays:grants: name, Capability, and Operation Declarations, with anylabelslibraries: name, version, source andneedsmessages: name (a Selector for a labelled message), argument Shapes and receiving kinds, with any documentationobjectKinds: name, properties andparentKinds, then itselementscollection declaration when it has oneobjects: well-known name and kind
- Musical time:
musicalTime: truefollows the arrays, only when the Host supplies a musical clock, so tooling can flag awaitin a Musical Unit that would raiseno musical time. - The Owner Kind:
ownerKindcomes last, only when present. It names one ofobjectKinds, and tooling treats themeof this kind of Script as an object of that kind. Without it, tooling leavesmeunknown.ExportManifestrefuses a kind that isn’t inobjectKindsasinvalid value. - One data model: Operation Declarations and Shapes use the same data model as the corpus’s
case.toml, written as JSON here and as TOML there. A Constant value inside them uses the Value Encoding. - Documentation: an Operation writes its
description, then itsexamples, after its other keys, each only when present. They are the only keyscase.tomllacks, and the only ones the Group Fingerprint leaves out, so rewording them changes the manifest’s bytes but not the Fingerprint. - Message documentation: a message writes its
description, then itsexamples, after its other keys, each only when present, as an Operation does. Tooling shows them for a Handler or command with the message’s name, such as one a Host answers at the end of every Message Path. - Order: declarations are ordered by name.
- Bindings: a Grant’s binding never appears.
- The Core never reads it, so a stale manifest can only mislead tooling.
Operation naming guide
Section titled “Operation naming guide”A call reads ask <capability> to <operation> <arguments>, so the Operation’s name finishes an English instruction to a noun. ask inbox to ask fails that test.
- A Capability is a noun (
http,inbox,ledger). An Operation is a verb or verb phrase that reads afterto(get,fetch,post,schedule,lookUp). - Read the call aloud.
ask inbox to fetch unreadworks, andask inbox to inboxdoesn’t. - Never repeat the Capability’s name in the Operation’s (
tell log to log). Usewrite,noteorrecordinstead. - Prefer one word. Use camelCase only when one word would be ambiguous (
lookUp,numberSymbols). - Name an immediate Operation for its result (
lookUp,count,tag) and a suspending one for its action (fetch,charge,submit). - An Operation name may be a keyword elsewhere (
put,delete, ADR 0012) or a stdlib name. Operation names are their own namespace, solocale’supperdoesn’t clash with theupperBuilt-in (ADR 0024).
DefineCapability refuses ask, tell, send, wait and end as Operation names, since the first four read badly on every Host and end closes a tell block (ADR 0063). The rest of the guide is advice.
Host conventions
Section titled “Host conventions”Non-normative (ADR 0030): HTTP header names are lowercase. A repeated header’s values are joined with , , except set-cookie, which is a list of text. For http’s HTTP Exchanges and fetch results these conventions are normative (chapter 7).
Non-normative: a peer transport between Hosts authenticates both ends with mutual TLS, and its binding pins each destination’s key. A browser Host, where client certificates are awkward, authenticates to its server with a session token, and the server’s Host derives the Caller Identity from it. Groups on one Host need neither (ADR 0154). The TS Host carries Remote Sends between a page and its workers over MessagePorts, and to a server over a WebSocket on which each end proves its key (ADR 0165). There each end’s first text message is {"hello": "<fingerprint>", "key": "<base64 SPKI>", "nonce": "<32 hex digits>"}, the browser’s with "token" too, and its second {"proof": "<base64 signature>"}: its key’s ECDSA P-256 SHA-256 signature, as the 64 bytes of r then s, over the UTF-8 text northtalk peer ws followed by the other end’s nonce and its own fingerprint. A key whose fingerprint isn’t the hello’s, a proof that doesn’t verify, or a server key that isn’t the one an address wss://HOST/PATH#FINGERPRINT pins closes the socket. Each message after that is one frame, of at most 16 MiB. The server’s Caller Identity is {key, via: "ws"} merged with what its authenticate gives for the token, and the browser’s {key, via: "ws", origin}.
Outside parity
Section titled “Outside parity”- Idiom: how each Core expresses the interface: errors or exceptions,
Start/Answeror a Promise, and the builders for maps. - Wording: a
HostError’s detail, and a diagnostic’s message. Their codes are normative. - Helpers built only on this interface, versioned with each Core: the drivers (
northtalk.org/go/driverin Go, with a worker pool, a run queue and a timer per Group, andnewDrivenGroup(core, options)andautoDrive(group)from@northtalk/ts/driverin TS), the plain JS Helpers from@northtalk/tsand@northtalk/ts/wasm(createGroup, a driven Group with explicit close and async disposal;script.handlersandhandlersOf, which call Handlers with plain JS values; andinlineGrants, which grants plain JS functions as Operations), theMust*value constructors, Trace file sinks and the corpus runner. Game Hosts pump by hand. - The TS Core’s debug-pause hook (ADR 0028, Appendix C).
- The message layer’s framing, and protocol errors (an unknown message, a malformed frame or an unexpected
ref), which are the transport’s. Its messages, fields and encodings are normative; a frame may not be refused solely for its nesting depth. - The Host Manifest is for tooling, and the Core never reads it.
- Host conventions such as lowercase HTTP header names.