Skip to content

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.

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

  • Core is 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, restore and 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.
  • Making a Group: NewGroup takes the Group’s name and, optionally, the seed of the generator random draws 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.
  • Group takes 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.
  • Script is 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.
  • Queued calls: Deliver, Request, Broadcast, Decide, DecideBroadcast, Call, SetParent, Dispose, Stop, CancelRun, RewindRun, Revoke, Answer, Fail, RequestCharge and Settle, and cancelling a Request, Decide or Call through its context or signal. They are safe from any goroutine. Each appends to the Group’s input queue, calls OnReady and returns at once, with a delivery id where it has one.
  • Host Objects: Object and ObjectByID are safe from any goroutine and from inside a Pump, such as from a property Get. They don’t queue: a handle is made, or found, at the call.
  • Script names: ScriptNames is 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: Libraries is 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 form RestoreOptions.Libraries takes. After ReplaceLibrary that 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, CancelRun and RewindRun land 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. A set through a property’s value is one crossing: no Stop, cancel or rewind lands between its walk, its Get and its Set. One made then lands after the Set’s prop record, or where the set raises (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: RewindRun ends 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 no catch or finally. 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 state rewound, 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 as not-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 a run end with outcome cancelled and no run or Handler. Plain Deliver has no cancellation context or signal; its delivery id alone cannot be used to queue cancel-delivery.
  • Durations: MaxPending and MaxWait are whole milliseconds. Go refuses a finer time.Duration, and TS a fraction, as invalid 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, Grants and Counters. 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 call in both Cores.
  • Host functions: Operation functions, property Get and Set, 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.

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.

  • The Clock is an argument: Pump(now, …) takes the Group’s one Clock reading, and Call.Now() returns it. A reading earlier than the last Pump’s is clock backwards. A game pauses by not pumping, and freezes time by passing the same now. TS’s nowMicros() reads Date.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 Request and Call futures settle as it finishes. Calls that end Runs outside a Pump (Reload and ReplaceLibrary) return their reports; Restore returns the accounting baseline in RestoreResult.reports.
  • The report kinds:
    • charge result, with request, call, requested fuel and status (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 sets fallback, and its handler is the message’s Selector. An errored Run’s error reaches the Host as a ScriptError: its code, its text message, and its other fields as its data. Its at is the raise that no Unwind Table entry caught, the Run’s last raise record, and a Limit Fault’s is its faulting instruction, the fault record’s: each gives the code unit, the frame’s Handler as an error’s at names it, the instruction index and the source position. Other outcomes have no at
    • stop
    • unhandled
    • call failed, which carries the Host-side detail of a host error the Script saw. If Stop or cancellation interrupts the Run at a property crossing, a getter or setter failure neither raises host error in the Script nor emits call failed; the property’s prop error record is still written. If Stop or cancellation interrupts the Run at an Operation crossing, a Host failure neither raises host error in the Script nor emits call failed; the call record is still written
    • effect failure, carrying Script, Run, named Grant, Segment, phase (abandon, begin, commit, rollback), status (failed, unknown), scope for abandonment, and optional Host-only detail; effect failed Run reports also identify the failure that prevented commit
    • decided, carrying a Decision’s Verdict (below)
    • the lifecycle and cumulative Run accounting reports

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 started and run discarded join ordinary reports in actual occurrence order; existing run end remains 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 exactly stop, reload, library replacement, variables-only restore or rewind. A message that never starts a Run has no invented Run id or lifecycle event.
  • Accounting tail: after lifecycle reports append one run accounting for every Run started, charged, ended or discarded in this call, ordered by Run creation order, then one causal work for every changed root in root Delivery admission order. The former’s state is live, terminal or discarded. 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. parentRun is the spawning Run even if it ends before dispatch; a call also supplies parentCall. 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 for Run 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. discardedMessages increases 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 started events. 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 introduce vars Host 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.

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, FromFloat and Dec in Go, and num and dec in TS.
    • A float becomes the shortest decimal that reads back as the same float, the digits ECMAScript’s Number::toString and Go’s strconv.FormatFloat(f, 'g', -1, 64) both give, so 0.1 stays 0.1.
    • NaN, ±Infinity, more than 34 significant digits and a magnitude of 10^34 or more are refused (chapter 3). -0.0 enters as 0.
    • Dec and dec read text exactly as as number does, one leading - included (chapter 3).
  • Numbers out: a number reads as an opaque Decimal. Its String() 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 Value is 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’s record(obj) refuses integer-like keys, since JS reorders them.
  • The other kinds:
    • Nothing is northtalk.Nothing in Go and the nothing constant in TS. The named constructors never accept null or undefined for it.
    • A Quantity is built from a Decimal and 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 date syntax, 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 a time.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.
  • The display form: String() and toString() give the display form (chapter 11).
  • Adding: Add(a, b) in Go and add(a, b) in TS apply the + rules of chapter 3 outside any Run, uncharged. Where + would raise, they fail with that error as a ScriptError, with its code and fields. A store Host applies increment deltas with them, so every Store adds as Scripts do (chapter 7).
  • Plain JS data: TS also has toValue and fromValue, which convert between Values and plain JS data by the named constructors and accessors (ADR 0119). toValue reads null and undefined as Nothing, arrays as lists, plain objects as record does, and a Map as map does. It refuses a JS number by default; { numbers: 'integer' } accepts only safe integers through num, while { numbers: 'decimal' } applies num’s shortest round-trip rule. Other numbers in integer mode throw invalid value naming dec() and { numbers: 'decimal' }. fromValue writes Nothing as null, a number as a Decimal, a list as an array and a map as a plain object, or as a Map when asked. Every other kind comes back as the Value.

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. zone is the id as given. The first change’s at is the window’s start and holds the offset in effect then, each later change is an Instant in the window where the offset changes, and until is 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, toCivil and toInstant with the result give what the Host’s calendar implementation gives for the same zone, if the Host offers one.
  • Plain JSON: DecodeJSON and EncodeJSON follow the JSON mapping of chapter 7, the rule the json Library 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 not 3.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). $map holds 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.
  • Scripts can’t reach the Value Encoding, and the Conformance Corpus uses the display form instead (ADR 0018).

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

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 kind in 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 a call failed report.
  • 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, check and explain check 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) and explain(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. conforms gives true exactly when the value fits. explain gives the explain Built-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 raises invalid shape.
  • Defining one: DefineCapability takes a name and its Operations, once per process. Each Operation is a declaration (name, argument Shapes and optional labels, result Shape, cost, mode, maxPending, declared error codes, optional scope, segmentBound and command metadata, and an optional description and examples) paired with the Host function that implements it. Declarations are ordered by name, whatever order the Host gives. ask, tell, send and wait are refused as Operation names.
  • Argument Labels: an Operation’s labels list 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): with labels = ["to"], ask world to move "pass" to "red hangar" calls move as ask world to move "pass", "red hangar" does (ADR 0115). Each must be an Argument Label word, and the list has one entry fewer than args; DefineCapability refuses anything else as invalid 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, its call record, 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 command may also be called as a Host Command, by its name alone. DefineCapability refuses command on 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 with GrantsAsUsed a Host Command call is a use of its Operation (ADR 0094).
  • Documentation: an Operation’s description is plain text and its examples are 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. A description that isn’t text, or examples that 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: Do runs at the call, inside the Run, and returns the result.
    • Suspending: Start runs at the call and returns at once, and the Host answers later with Answer, AnswerWithCost or Fail, from any thread.
    • Fire-and-forget: Fire runs at the call, in order, and its result is dropped. Only these can be called with tell … to. A tell block calls each Operation in its own mode (ADR 0063).
  • Grants: a Grant is a set of a Capability’s Operations with the Host’s own binding data, which each call reads. Load binds 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’s needs and implicit abandonment dependencies; say uses console.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 Grants returns 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, http and peer have their declarations fixed by chapter 7. Their factories take Host implementations, except for clock, 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 Error invalid 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. A timer implementation must supply both schedule and cancel, and a console implementation both write and read, a calendar implementation all six of its methods, a locale implementation all eight, a store implementation all eight Operations, all three lifecycle hooks and release, a sqlite implementation all five Operations and coordinator, a user implementation all four Operations, an http implementation all three server Operations, fetch, or both, and a peer implementation all five Operations; a missing method is also invalid value. Every Core defines every Standard Capability, and a Host offers the optional sqlite, user, http and peer only by calling their factories.
  • The store factory: its Grant’s binding is the Store’s name, as text. set, delete, increment and swap are declared Segment-bound, so the factory maps every binding to the implementation as one Segment Coordinator, whose begin, commit and rollback receive 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 checks invalid key, invalid watch validation and the result kinds. watch and unwatch are immediate and not Segment-bound; the factory passes the effective message (storeChanged for omitted or Nothing) to watch, 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, and StoreCoordinator(impl) gives it in Go, so a sqlite implementation 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.
    • Charge draws 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’s Data, as a result is.
  • Failing: a Fail, or a returned ScriptError, raises its code in the Script, with its message and its Data’s entries as fields (chapter 6). Data must be a map or Nothing. Any other value is a malformed Host failure: the Script raises host error, and the Host-side detail goes only in the call failed report. 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 a Data key that is reserved, also becomes host error. So does any other error the Host function returns.
  • Waiting: a suspending call past its maxPending, or else the Script’s MaxWait, fails with timeout and 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 Call belongs to its Group: its Answer and Fail reach only the Group that made it, never a Group restored from a save of it. A restored Group is answered through the Calls that Settle returns, and only the message layer’s answer and fail, which name the Group and the call id, can reach it for a call it no longer holds (chapter 10).
  • Revoking: Revoke takes effect when its queued input is drained. It affects only that Script’s named Grant, makes later calls through it raise capability revoked until 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.

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.

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 stop and reload, 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 by revoke or disable are included, since the hook is idempotent for the Host.
  • When, relative to other cleanup: for stop and reload, after abandoning the Script’s scopes and rolling back its participant, and before the stop report, the replacement code or any later execution. For disable, right after the effect failure report for the failed abandonment. For revoke, 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 Reload or ReplaceLibrary outside one. It may queue inputs but can’t make worker calls, which are reentrant 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 release as an interim reply to pump, reload or replace-library, with script, grant, reason and now, and the Host answers release-result with 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.

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 bars calls wait with 8 bars, as an ask … and wait would, through a Grant every Script of the Group holds under the reserved name musical-clock. A - can’t be part of a Name, so no source can name that Grant, so ask, tell, revoke and GrantsAsUsed never see it. Everything else follows from its being a pending call: its call and answer records in the Trace, its place in a save, its abandonment on Stop, Reload and cancellation, and the release hook’s stop and reload calls.
  • 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, wait in a Musical Unit raises no musical time (chapter 5).
  • Making one: DefineCapability refuses wait as an Operation name, so the Core makes the musical clock from the Host’s wait function, the Operation’s cost and an optional release hook: in TS musicalClockCapability(impl, costs, release?), in Go (*Core).MusicalClockCapability(impl, costs, options...), and in C talk_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 with define-capability’s musicalClock: true instead of standard, and the Core supplies the fixed declaration.
  • Supplying one: in TS the Group option is musicalClock, and in Go WithMusicalClock(clock), a GroupOption that NewGroup and Restore take. A C Host, and a message-layer Host, grants the clock to each Script under musical-clock at load and restore. The Group Fingerprint includes its Operation Declaration; the Host Manifest writes musicalTime: true instead.

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

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}. database is the Host’s name for the database, and a Script never sees it. tables is 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 Error invalid value when 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 value from 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: query and change charge their declared cost, then authorize every statement step through a factory-supplied beforeStep callback that draws perStep. 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 precharge max.
  • Coordinators: the factory calls the implementation’s coordinator with a Grant’s database once, when the Grant is created, and the implementation gives the same coordinator for the same database. change, begin, commit and rollback are 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: begin is declared to open transaction with abandon = rollback, and commit and rollback to close it, so the Core keeps the scope’s slot and abandons it as the lifecycle contract requires.
  • SQL values: the implementation sees NULL as nil in Go and null in TS, INTEGER as int64 and bigint, REAL as float64 and number, TEXT as string, and BLOB as []byte and Uint8Array. The Core converts params into these by the rules of chapter 7, a list into a positional list and a map into a name map, keyed without the colon. params is declared with the Shape any, so a Function Value anywhere in it raises not encodable. After the Shape checks, the Core checks max, then that params is a list or a map, then each value in it, in order. Either of another kind raises wrong kind as a Shape check would, with argument 2: params itself with expected "list or map", and a value in it with expected "nothing or number or text or bytes or boolean" and path its position or key.
  • Results: the implementation gives {columns, rows}, each row a list of SQL values in column order, and change also gives changes. The Core converts each value and builds each row’s map in column order. It raises sql for a column named twice, with reason "duplicate column " and the name, and unrepresentable for 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 with column its 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 than max or a negative changes ends the call as host error. Neither error the Core raises here carries a message. 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.

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 ?NNN in order, and a name map binds :name. The number of parameters given must equal sqlite3_bind_parameter_count. A statement with @name or $name, one that mixes positional and named placeholders, a name map for positional placeholders and a list for named ones all fail with sql, and nothing runs.
  • The authorizer denies BEGIN, COMMIT, ROLLBACK, SAVEPOINT, RELEASE, ATTACH, DETACH, VACUUM INTO and load_extension. It allows only the read forms of the PRAGMAs table_info, table_xinfo, index_list, index_info, index_xinfo, foreign_key_list and user_version, and denies every other PRAGMA. It denies reading or writing any table outside the binding’s tables, and a co-located Store’s table, for reads too. A denial fails with sql, and nothing runs.
  • Read-only queries: query prepares its statement and checks it with sqlite3_stmt_readonly before stepping it. A statement that could write fails with not read-only, and nothing runs.
  • Row limit: a call gives at most max rows. Its statement is stepped no further than max + 1 rows, and one that gives more fails with too many rows, with max.
  • Atomic calls: a call that fails leaves the database as it was before the call, including a change that fails with too many rows after its changes were made.
  • Constraints: a broken constraint fails with constraint, with kind from SQLite’s extended result code: unique, primary key, not null, check, foreign key, datatype or trigger for SQLITE_CONSTRAINT_UNIQUE, _PRIMARYKEY, _NOTNULL, _CHECK, _FOREIGNKEY, _DATATYPE and _TRIGGER, and other for every other.
  • Other errors: any other SQLite error fails with sql, with reason SQLite’s error message.
  • Text out: in TS, the implementation decodes TEXT as UTF-8 with a decoder that fails on invalid input, and TEXT that isn’t valid UTF-8 fails with unrepresentable, with column its column’s name. It never gives a replacement character.
  • The Segment’s transaction: the coordinator’s begin hook only prepares the Segment’s state and never takes a lock, since a failed begin hook raises host error. The Segment’s first change or begin opens its database transaction and takes the database’s write lock. commit publishes the transaction, and rollback discards it. A commit that SQLite refuses, such as for a deferred constraint, returns failed.
  • Script transactions: the begin Operation opens a savepoint inside the Segment’s transaction, commit releases it and rollback rolls back to it and releases it.
  • Contention: a change or begin that needs the write lock while another Segment holds it fails with sqlite busy before 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 change does, and fails with store busy, with key, while another Segment holds it.

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, unserve and respond together, 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, is invalid 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 (httpRequest for omitted or Nothing) and an omitted options as an empty map. The Trace keeps the call as the Script wrote it, as for a store watch.
  • Answering: serve starts a suspending call, answered with {host, port} once the listener listens, or failed with address in use or bad address. unserve and respond are immediate.
  • fetch’s implementation receives the normalized URL as text, with query added, and the request map without query: method always present, headers as given, body as given, and json as its compact JSON text, as respond’s does. It adds the default content-type and accept-encoding, checks the origin against the binding, and answers with {status, headers, body} or fails with bad address, network error or response 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 leave fetch out.
  • not owner: the implementation compares the Call’s delivery id with the one it Delivered the HTTP Exchange under, and fails respond with not owner when they differ or the Call has none.
  • Result checks: a serve answer that isn’t a map of text host and whole-number port ends the call as host error, and so does a fetch answer that breaks chapter 7’s response rules.

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.Deliver to 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 started for an exchange’s delivery names its Run. A run end for that Run that leaves the exchange unanswered answers it: 404 for unhandled, 503 for cancelled or dropped, and 500 otherwise. A Delivery that ends unhandled without a Run, or a run 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 MailboxFull is 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 closed reads true and respond fails with exchange 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.

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 reach and expose, how each resolves, and how each destination is authenticated. The Core never reads it.
  • One Grant: Load refuses a Script given two Grants whose Capability is peer, as invalid value.
  • The kind peer is defined by the Core, with no properties. The implementation makes each Peer with group.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: expose and reach start suspending calls. reach is answered with the Peer, or failed with bad address or not exposed; expose with the Peer for the exposure, or failed with bad address or name in use. expose hears its name, or none for an unnamed exposure. unexpose hears a name or a Peer. unexpose and caller are immediate, and post fire-and-forget.
  • post and call hear 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 answers call with the receiver’s reply, or fails it with send failed and {reason, error}.
  • Release: the implementation hears its Grants’ releases (the Grant release hook) through release in TS and a Release(GrantContext) method in Go, and its Peer Router withdraws Peer Exposures by them.
  • caller gives the Caller Identity the implementation recorded for call.delivery when it gave a Remote Send to the Exposed Script, or Nothing when the call has no delivery or the Delivery wasn’t a Remote Send (ADR 0125). When a call is abandoned the implementation drops its reply when it comes; it never asks the receiver to stop.

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, revoke or disable withdraws every Peer Exposure, named and unnamed, that the released owner’s named Grant made, before the hook returns. A release with reason reload keeps them. Withdrawing one is as unexpose does: a Remote Send already delivered is unaffected, a later call fails with not exposed and a later post is 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/peer in TS and northtalk.org/go/peer in Go supply one.
  • Delivery: a post that arrives is one Script.Deliver to the Exposed Script, and a call one Script.Request, each under the Selector and arguments sent, with no limit override. A Remote Send that comes after its exposure is withdrawn is not 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 call arrived, it fails it with unreachable.
  • Replies: a Request that settles answers the call with its result. One that rejects with send failed fails the call with the same reason and error. A Script.Request refused as MailboxFull fails it with reason mailbox full, and any other refusal, or a reply that can’t be carried back, with unreachable.
  • 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 send and a Run’s result that holds one fails the call with unreachable and a call failed report 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 pending call with Fail, send failed and reason unreachable, 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.

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 message and each items entry as text, multiple as a boolean, and an omitted prompt, default or title as empty text. A Nothing option is an omitted one, since each options key is optional.
  • Answering: confirm, choose and enter start a suspending call, which the implementation answers with Answer or Fail. notify is fire-and-forget.
  • user busy: the implementation fails a confirm, choose or enter with user busy while the same Script has another one it hasn’t answered. It reads the Script from the Call, 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 for enter, and Nothing, text or a list of texts for choose) ends the call as host error. So does a choose answer that isn’t an item, a text answer under multiple: true, a list answer without it, and a list that isn’t a subsequence of items. The call failed report carries the detail, as for any result that breaks its Shape.

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 Get and optionally a Set, 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, with capability the Object Kind’s name and operation the property’s. A value set that breaks the Shape raises wrong kind before the Set runs. A property with no Set is read-only (chapter 4). A set below a property, such as set the isLocked of the door of me to true, calls the property’s Get and then its Set, each charged and traced as on its own; only the Set’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 is duplicate object id. An optional parent gives 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, or wrong group, and not disposed, or invalid value. A refused call makes no object. Making an object with a parent writes an object record 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 fits DecodeValue’s resolver (ADR 0058). The Core holds the kind and id, so a Script reads them with objectKind(o) and the id of o without 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 is parent cycle; changing a disposed child’s parent is invalid 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, writes refused, and adds a Host-error report to that Pump (*HostError in 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.
  • Load compiles 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 a LoadError, with its diagnostics (chapter 2).
  • Inline source in TS: the talk template 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:page1 and element: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, and AddLibrary and ReplaceLibrary add it to a Group (chapter 7). ReplaceLibrary also recompiles every Library that imports the replaced one, and a Host reads the recompiled ones with Libraries.
  • 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 error can'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 LimitOverride field always overrides; a zero field overrides only when its corresponding bit is marked in Set (for example, Set: OverrideFuelPerRun with FuelPerRun: 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.

  • 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 as invalid value (ADR 0055).
  • Deliver routes a message to an object’s Owning Script, or the nearest ancestor that has one, and Script.Deliver addresses a Script directly (chapter 5). Each returns a delivery id, which the Run it starts reports.
  • Request is a send … and wait from outside. Its future settles with the Run’s result, or rejects with send failed, its reason, and for an errored Run its error. Cancelling its context or signal queues cancel-delivery. TS’s Script.invoke(name, ...args) is a Request that returns only its result promise, with no delivery id or signal. It is not Call, which calls a Function Value.
  • Broadcast reaches every Script that wants the message when the queue is drained. Each recipient’s run end carries its own delivery id and the broadcast id.
  • Call calls a Function Value (Function Values), and Decide asks 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, a SetParent queued 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.
  • 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 until for 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, script or library, 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 first use line that names it, then a line source followed 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 a use line that names a Library the Group doesn’t hold adds none, so a load that 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"}:
    • libraries is each Library the Host added, as [name, identity], ordered by name. The stdlib Libraries aren’t listed, since the language version fixes them.
    • scripts is each Script’s {"name", "identity", "grants", "limits"}, followed by "forbidSuspension": true only for a Script loaded with it, ordered by name. grants maps 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). limits maps each limit’s ts name in limits.toml to the value the Script has after defaults, durations in whole milliseconds, ordered as in limits.toml.
    • Each granted name maps to {"capability", "operations"}. Operations are ordered by name, with keys name, mode, args, optional labels, optional result, cost, optional maxPending, optional errors, optional scope, optional segmentBound, optional command, optional metering, in that order. Missing args is []; cost has fuel, then alloc, with missing allocation written as 0. maxPending is whole milliseconds and appears only when declared on a suspending Operation. A scope writes {"opens", "abandon"} or {"closes"} in that key order; segmentBound and command appear only as true, with absent and false equivalent, and labels only when it isn’t empty. Bindings, Host functions, lifecycle hooks, description and examples are excluded. Omitted errors stays 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}. The object wrapper names an Object Kind. A map Shape is {"map": [field, …]}, followed by "open": true only for an open map. Each field, including an error field, has key, shape, then optional: true only 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 in disabledGrants, sorted in Unicode code-point order and omitted when empty, and forbidSuspension: true for 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’s wait and until are the end reason and deadline its seg record wrote, so a call’s maxPending or MaxWait gives no until, and its calls are the call ids, reply ids or Join Members it still waits for. It charges nothing, and is the Host Input vars in the Trace (chapter 11). A REPL’s :vars, :runs and :mailbox render it (chapter 12).

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 internal error message with no Handler starts no Run either.
  • Faults: Runs that ended with the outcome limit fault, once per Run. Ordinary errors, effect failures, Stop and cancellation do not increment it; a Cleanup Budget failure still ends cancelled.
  • 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).

  • What the Host holds: a Function Value is an ordinary Value of kind function. 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 gives host 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.Call has the shape of Request. It is a Delivery to the Home Script, recorded in the Trace as a call-value Host Input (chapter 11).
  • Staleness: checked when the queue is drained. A stale value rejects with send failed, reason function 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 errored with wrong arity at the body’s first instruction, without executing or charging that instruction or unwinding a frame; the function’s catch and finally regions do not apply. The Request rejects with send failed, reason errored. 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’s handler readout 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 function Shape, or value when 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 timer Capability’s are.

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) and group.DecideBroadcast(ctx, m) are queued, like Request. They return an id and a Deciding future that settles with a Decided.
  • The Verdict: allowed, vetoed or undecided. Decided also 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 , deciding Run that the Decision reaches. The Pump that seals it returns a decided report. 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, so defer 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 the decided report, since an allowed Run may go on. A Decision that reaches the end of its Message Path is allowed, and unhandled is reported as usual.
  • Not durable: like Pending, the future doesn’t survive a restore. The decided report still arrives with the same id.

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.go is one JSON message with a reply, or a negotiated binary frame. request-pump-fields-v1 carries Request, Function call and Pump exchanges, including explicit combined admission/Pump worker calls; binary-frames-v1 is 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: RequestPump and CallPump (TS: requestPump and callPump; Elixir: request_pump and call_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 structured PumpedRequest distinguishing admission failure from Pump failure with the retained requested handle. Elixir returns a NorthTalk.Pumped holding a NorthTalk.Pending handle 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 to reload or replace-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-in group-exchanges-v1, an open need holds up only its own Group’s exchange. With the opt-in binary-frames-v1, every frame after hello is 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 full is 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-run and rewind-run land at the latest at the running Pump’s next op or prop, or at its end. The Trace records where.
  • Restore bindings: restore-bindings-v1 advertises registration of Capability declarations and Grants while a resolve need is open. Those registration exchanges use refs distinct from the restore’s; resolve-result keeps the restore ref. Other exchanges remain blocked. The successful restore reply also includes scripts in load order, objects as all retained [kind, id] identities (including disposed ones), and each pending Call’s capability, run, segment and now, 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 abandoned field of a final successful pump, reload or replace-library reply lists, in call id order, the suspending calls the Host answered started that 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’s Call gives: the Host stops the call’s work and drops its queued answer or fail. One sent anyway is a late answer, recorded and ignored. A Host opting into abandoned-before-needs-v1 receives 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 op carries the Fuel the Run has left after the declared cost. The Host’s Charge subtracts from it locally and fails exactly when it would go below 0, and its reply carries the total accepted charged. Refusal is latched and uses a limit reply even after earlier increments succeeded. After started, local fuelLeft is no longer authorization: asynchronous metering uses request-charge and 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 raises wrong group before it sends another Group’s object.
  • Function Values cross as {"$function": [home, display, token]}. With function-metadata-v1, Core-to-Host values instead use {"$function": [home, display, token, name, required, total, unit]}: unit is the defining code unit’s 32-byte identity as a Value Encoding byte string, name is the declared name, or null for a Lambda, and required and total are nonnegative integer parameter counts, with required <= 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 without unit, 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 checks wrong group when it reads a token, and function gone when the queue is drained. A token belongs to the Group instance that wrote it: a restored Group, even one restored under the same handle after drop-group, is a new instance, and reading an earlier instance’s token is wrong 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 by unit, using script-units before 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 whose message the Core wrote (chapter 6) instead crosses as {"$coreError": [[key, value], …]}, in order, whatever its keys, so a Host that renders the Trace can leave that message out as the Core does. A run end’s error is 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 text message is invalid value, and so is the tag without opt-in. Host storage refuses it.
  • Never crossing: Grant bindings, native objects, OnReady and futures stay on the Host’s side.

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’s Report union 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 accounting and causal work. The latter four use the fields in Run accounting; fn and args carry Value Encoding values. A Host opting into climb-v1 also gets climbed: true on the run end of a Run whose message went on up the Message Path, by pass or with no clause taking it. That Run hasn’t answered its asker, so the Host keeps the Request or Decide future open until a later run end, unhandled or decided report settles it. An in-process Core knows this without the field. With function-gone-v1, a Pump reply’s gone lists the delivery ids of Host Calls found stale at the drain, which end with no report: the Host rejects each with send failed, reason function gone.
  • Encodings: now and nextDeadline are $instant text, 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 carries trace, 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, and talk_send(n) returns the reply’s pointer and length packed as ptr << 32 | len. A sidecar sends each frame as a 4-byte big-endian length, then the JSON, both ways on stdio. The opt-in chunked-wasi-v1 transport 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.

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-entry decides one Entry. handlers are the first Names of the Session Script’s Handlers, so that a Command Call to one is a statement; bound are the names the Script already has.
    • kind is declaration, statement, expression, or empty for blank input or a lone --| block.
    • doc is attached when a --| block directly precedes the Entry’s first line, pending when nothing has followed the block yet, and none otherwise; a blank line after a block detaches it. The Session Host refuses an attached block before anything but a declaration other than use.
    • problem is the first syntax error: {code, line, col, endLine, endCol, incomplete, trailing}, positioned in the Entry’s own lines, with its range (chapter 2). incomplete means more lines could complete the Entry, as a REPL waits for them (Fenced text in sessions and tooling); trailing means a whole statement or expression was followed by more input. Load-time diagnostics still come from load, extend or reload.
    • declarations are a declaration Entry’s, as analyze-source gives them. An Entry has exactly one; :fix accepts several.
    • implicit are a statement’s or expression’s implicit Script Variables, in the order first bound, without the bound names.
  • analyze-source lists a source’s declarations in order, or its first syntax error as problem. Each is {kind, name, word?, private, span, signature, doc, arity?, initializer?, imports?}:
    • kind is handler, function, constant, variable or use. name is a Handler’s Selector or any message, and a use line’s Library; word is a Handler’s first Name.
    • span is {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.
    • signature is its head: through the end of a function’s or Handler’s first line, or constant x and script variable x. doc is the --| block straight before it, each line without its indentation, --| and one space, joined with LF.
    • arity is a function’s [required, total] parameters, initializer a Script Variable’s text after =, and imports a use line’s [{name, local}].
  • analysis-catalogue gives the Built-in catalogue :describe and :apropos read, the Standard Library’s sources and the normative :inspect reader template.
  • message-name says whether a send could compute name for arity arguments: a Name, or a Selector with one part per argument. :trace and :describe check 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.

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. clock starts the session’s Clock; real is the default. limits are those :limits sets. objects, present even when empty, means the Host serves live Host Objects: its texts are the kind, object and setup envelopes it declares. Between Host calls, a session-input envelope declares more, or is a Host action: an input envelope with its request alone, which the session performs at once and records with its reply. A transcript replays 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 refuses session-open, naming the line. A recorded Transcript declares its own objects, so objects must then be empty.

  • Readings. Under a real Clock, every session-input and session-pump carries reading, 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 read line, a user prompt’s answer or a deadline stays open, and the reply says so. A session-input line or answer goes on with it; a session-pump Pumps 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, a session-pump is a Pump at a deadline, as a Transcript’s @ line outside any other input. A user prompt while another waits is answered user busy at once, and recorded.

  • Needs. Three answers are needs, answered under the asking frame’s ref, and each stays open across frames: while one is, session-input, session-pump, session-describe-prompt, session-complete and session-inspect are refused, and session-close abandons it.

    • prop is a live crossing, as a Group’s: the Pump waits at its Crossing Pause. prop-result gives one outcome, value (V), ok, fail or hostError, and optional envelopes: what the Host did before answering, in order, as declarations of identities its answer names and Host actions. Each is recorded before the crossing’s property-end, a refused action with its refusal.
    • resolve, with objects: [[kind, id]], is a live Restore asking whether each identity still resolves. resolve-result gives objects: booleans.
    • write, with directory, name and data, is a file :export or :store save writes. write-result gives written: whether it was.

    After a resolve or write answer, 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 (prompt when nothing is open, read, user, deadline, or need), clock (real or virtual), and deadline, the next deadline’s $instant text under a real Clock, or null. Beside ok or need, every session reply carries output, the lines the session printed; trace, its Group’s Trace lines; and transcript, its Transcript Items as a Transcript’s lines, in the order the session made them.

  • Inputs. An input is one Entry or Session Command, with any further lines in more, as a Transcript’s | lines hold them; a command that names a file carries the file’s lines there instead. session-complete tells a Driver collecting lines whether text is whole yet, as Fenced text in sessions and tooling reads it with the session’s own names, so it knows when to send it. :help and :quit are the Host’s, and aren’t recorded.

  • Inspecting. session-inspect gives inspect’s reply for the session’s Group, as a Trace Case ends, and its trace holds the Group’s snapshot. It is no input, and records nothing: :vars is the Session Command a Transcript holds. A Function Value’s token is empty, since no message takes it back.

  • Prompts. session-describe-prompt gives the waiting user prompt: its call, kind (confirm, choose or enter), and its message, prompt, default, items and multiple, each empty or false when its Operation has none. An answer is {shown, fail}: the value in the display form, or with fail: true an error map.

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 file: ExportManifest writes one JSON file per kind of Script, named <kind>.talk-manifest.json. The same definitions always give the same bytes.
  • Its fields: kind, version and language, then these arrays:
    • grants: name, Capability, and Operation Declarations, with any labels
    • libraries: name, version, source and needs
    • messages: name (a Selector for a labelled message), argument Shapes and receiving kinds, with any documentation
    • objectKinds: name, properties and parentKinds, then its elements collection declaration when it has one
    • objects: well-known name and kind
  • Musical time: musicalTime: true follows the arrays, only when the Host supplies a musical clock, so tooling can flag a wait in a Musical Unit that would raise no musical time.
  • The Owner Kind: ownerKind comes last, only when present. It names one of objectKinds, and tooling treats the me of this kind of Script as an object of that kind. Without it, tooling leaves me unknown. ExportManifest refuses a kind that isn’t in objectKinds as invalid 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 its examples, after its other keys, each only when present. They are the only keys case.toml lacks, 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 its examples, 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.

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.

  1. A Capability is a noun (http, inbox, ledger). An Operation is a verb or verb phrase that reads after to (get, fetch, post, schedule, lookUp).
  2. Read the call aloud. ask inbox to fetch unread works, and ask inbox to inbox doesn’t.
  3. Never repeat the Capability’s name in the Operation’s (tell log to log). Use write, note or record instead.
  4. Prefer one word. Use camelCase only when one word would be ambiguous (lookUp, numberSymbols).
  5. Name an immediate Operation for its result (lookUp, count, tag) and a suspending one for its action (fetch, charge, submit).
  6. An Operation name may be a keyword elsewhere (put, delete, ADR 0012) or a stdlib name. Operation names are their own namespace, so locale’s upper doesn’t clash with the upper Built-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.

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

  • Idiom: how each Core expresses the interface: errors or exceptions, Start/Answer or 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/driver in Go, with a worker pool, a run queue and a timer per Group, and newDrivenGroup(core, options) and autoDrive(group) from @northtalk/ts/driver in TS), the plain JS Helpers from @northtalk/ts and @northtalk/ts/wasm (createGroup, a driven Group with explicit close and async disposal; script.handlers and handlersOf, which call Handlers with plain JS values; and inlineGrants, which grants plain JS functions as Operations), the Must* 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.