Host protocol v1

tinyscript has no ambient clock, randomness, console, filesystem or network. Every interaction with the outside world crosses a single definite-length CBOR request-and-reply boundary owned by the host, using buffers the caller supplies and owns.

Read buffer rulesRun conformance tests

Request and reply frames

Every protocol exchange consists of a 4-element request frame from the engine and a 3-element reply frame (normal value or thrown error) from the host.

FrameDirectionSyntaxMeaning
Request frameengine-to-host[1, requestId, method, arguments]Emitted by the engine when a call stops with TA_TINYSCRIPT_EFFECT. The host inspects outcome.message (a borrowed byte view) and sends a matching reply with the same requestId.
Value reply framehost-to-engine[1, requestId, result]Delivered by the host via ta_tinyscript_reply to resume a parked EFFECT with a return value. Invalid, stale or malformed replies return INVALID and leave the request pending.
Thrown reply framehost-to-engine[2, requestId, error]Valid only in response to tinyscript:host request(method, args). Causes the parked request() call to throw the decoded error inside guest code, where try/catch may handle it. Refused with INVALID on built-in scalar methods.
Protocol version 1 frames (CBOR).

When a thrown reply carries a CBOR map, the engine turns that map into an Error object (passing Error.isError) before throwing it. Any non-map value (string, number, array, null) is thrown verbatim. Built-in classes: Error, EvalError, RangeError, ReferenceError, SyntaxError, TypeError, URIError, SuppressedError, AggregateError.

  • If the map has an own string key "name" matching one of the 9 built-in Error classes above, the prototype is set to that class's prototype and the own "name" property is removed so it inherits the class name.
  • If "name" is missing, not a string, or does not match a built-in Error class, the prototype is Error.prototype and any custom own "name" property is preserved.
  • If the map has an own "message" property whose value is a string, it is converted into a non-enumerable own data property, matching new Error(message). Non-string "message" properties are removed.
  • All other own fields on the map (such as "code" or "status") remain own enumerable properties on the thrown Error object.

CBOR wire profile and values

Every protocol message is one definite-length CBOR item (RFC 8949) using minimal integer and length encodings, with no trailing bytes. Structured host requests, slot transfers and globals snapshots share one JavaScript-to-CBOR data model.

  • Definite lengths onlyEvery array, map, text string and byte string must carry a definite length. Indefinite-length items (additional info 31) and break stop codes (0xff) are invalid.
  • Minimal CBOR headsEvery major-type argument (integers, lengths, tags) must use the shortest width that represents it: 0..23 inline, 24..255 in 1 byte, 256..65535 in 2 bytes, 65536..4294967295 in 4 bytes, and larger in 8 bytes. Non-minimal encodings such as 0x18 0x05 are rejected.
  • Exact framing with no trailing bytesEach buffer contains exactly one top-level CBOR item. Any unread trailing byte after the root item makes the frame invalid.
  • Negative zero preservedIEEE 754 negative zero (-0) never collapses to integer 0; it is encoded as CBOR binary64 (0xfb 80 00 00 00 00 00 00 00). NaN is canonicalized to quiet NaN (0xfb 7f f8 00 00 00 00 00 00) on encode.
  • Canonical BigInt magnitudesBigInt values always encode with CBOR tag 2 (non-negative) or tag 3 (negative, representing -1 - magnitude) wrapping a minimal unsigned big-endian byte string with no leading 0x00 byte (empty byte string for 0n and -1n).
  • Unique UTF-8 text map keysCBOR maps represent plain JavaScript objects. Every key must be a valid UTF-8 text string, and duplicate keys within the same map are invalid.
ValueCBOREncodeDecode
Safe integer NumberMajor 0 (unsigned) or Major 1 (negative)Structured encoding writes integral Numbers in [-9007199254740991, 9007199254740991] (excluding -0) as minimal major 0 or major 1 integers. Scalar built-in adapters may also write integral Numbers as binary64.Major 0 values up to 2^53 - 1 and major 1 values down to -(2^53 - 1) decode to Number. In structured trees, integers outside the safe range (up to 64 bits) decode to BigInt; scalar service replies reject integers outside the safe range.
Floating-point Number0xfb (binary64); 0xf9 (binary16) and 0xfa (binary32) accepted on structured decodeNon-integers, -0, values outside the safe integer range, ±Infinity and canonical quiet NaN encode as 0xfb followed by 8 big-endian IEEE 754 bytes.Structured replies and slots accept binary16 (0xf9), binary32 (0xfa) and binary64 (0xfb) and promote them to binary64 Number. Scalar built-in replies (clock.now, random.next) accept only major 0/1 safe integers and binary64 (0xfb).
BigIntTag 2 (positive) or Tag 3 (negative) + Major 2 bytesAlways encoded with tag 2 (non-negative) or tag 3 (-1 - magnitude) even when the magnitude fits in a CBOR integer. Byte string is minimal unsigned big-endian with no leading 0x00 byte.Validates tag 2 or 3 wrapping a major 2 byte string with no leading 0x00 byte. Empty bytes decode to 0n (tag 2) or -1n (tag 3).
StringMajor 3 (UTF-8 text string)JavaScript UTF-16 code units are encoded to UTF-8; unpaired surrogates are replaced with U+FFFD.Must be valid UTF-8; malformed UTF-8 sequences are rejected as INVALID.
Boolean0xf4 (false), 0xf5 (true)false encodes as 0xf4; true encodes as 0xf5.0xf4 decodes to false; 0xf5 decodes to true.
Null0xf6null encodes as single byte 0xf6.0xf6 decodes to null.
Undefined0xf7undefined (including sparse Array holes) encodes as single byte 0xf7.0xf7 decodes to undefined.
ArrayMajor 4 (definite array)Encodes elements 0 .. length - 1 in index order; holes encode as undefined (0xf7).Creates an Array with elements in order. Declared element counts larger than remaining input bytes are rejected immediately.
Plain object (record)Major 5 (definite map, text keys)Encodes own enumerable non-hidden string and numeric keys as UTF-8 text keys. Rejects cycles, symbols, private fields, functions and Promises.Creates a plain Object with own data properties. Rejects non-text keys and duplicate keys in the same map.
Byte stringMajor 2 (definite byte string)Used only by built-in console.write for UTF-8 text and joined CLI arguments. Not emitted in structured CBOR data trees.Accepted by hosts handling console.write. Rejected with UNSUPPORTED in structured CBOR trees (tinyscript:host replies, slots, globals).
JavaScript-to-CBOR value encoding and decoding rules.
Rejected inputStatusBehaviour
Indefinite-length item or non-minimal CBOR headINVALIDRejected before allocation by ta_cbor_read_head.
Trailing bytes after root CBOR itemINVALIDRejected; frames must consume the entire input slice.
Duplicate key or non-text key in CBOR mapINVALIDRejected during import; heap allocations unwind atomically.
Leading 0x00 byte in tag 2/3 bignum magnitude or unsupported CBOR tagINVALIDRejected as non-canonical or invalid tag.
Malformed UTF-8 in text stringINVALIDRejected by ta_tinyscript_decode_utf8.
Cyclic object, function, Symbol, Promise or private field on exportUNSUPPORTED (guest TypeError on request)Refused before emitting a request frame; slots and globals return UNSUPPORTED.
Byte string (major 2) inside structured CBOR reply or slotUNSUPPORTEDOnly scalar console.write requests carry raw major 2 bytes.
Inputs rejected by both sides.

Built-in and custom service methods

Three built-in service methods cover ambient JavaScript capabilities (output, clock and randomness). All other host interactions pass through embedder-defined methods imported from tinyscript:host.

MethodArgumentsResultConstraints and buffers
console.write[number | bigint | bytes]nullReply must be [1, requestId, null]. Any other result kind or a thrown reply [2, ...] is rejected with INVALID and leaves the request pending. Encoded into the session heap gap (or overflow block); does not require ta_tinyscript_set_host_buffers.
clock.now[]integer number (ms since Unix epoch)Reply must be [1, requestId, number] where number is an exact integer in the ECMAScript Date range [-8640000000000000, 8640000000000000], encoded as a safe CBOR integer or binary64. Fractional, out-of-range, NaN, non-numeric or thrown replies are rejected with INVALID. Encoded into the session heap gap (or overflow block); does not require ta_tinyscript_set_host_buffers.
random.next[]number in [0, 1)Reply must be [1, requestId, number] where 0 <= number < 1, encoded as safe CBOR integer 0 or binary64. Negative zero is normalized to +0. Values < 0, >= 1, NaN, non-numeric or thrown replies are rejected with INVALID. Encoded into the session heap gap (or overflow block); does not require ta_tinyscript_set_host_buffers.
tinyscript:host request(method, args)Array of structured CBOR valuesany structured CBOR value, or thrown reply [2, requestId, error]method must be a non-empty string and args must be a JavaScript Array containing only CBOR-encodable values; invalid guest calls throw a guest TypeError before emitting any frame. The host authorizes methods by name and returns [1, requestId, value] or [2, requestId, error]. Requires ta_tinyscript_set_host_buffers(realm, packet, scratch). Request is written into packet using scratch for iterative tree walking; without host buffers or if packet/scratch is too small, the run ends with TA_TINYSCRIPT_LIMIT.
Service methods, reply constraints and buffer placement.

Session slots and globals exchange

Between calls, a host exchanges individual values through realm slots (ta_tinyscript_write_cbor_slot and ta_tinyscript_read_cbor_slot). It can also hibernate and restore all global and script lexical state as one CBOR map via ta_tinyscript_read_globals and ta_tinyscript_write_globals.

KeyShapeMeaning
"g"{name: value}Global object own data properties created by the session that are enumerable, writable and configurable (or declared by script var), excluding built-ins unchanged from the image, host-owned globals and script-declared functions.
"l"{name: [kind] | [kind, value]}Script environment lexical bindings where kind is "let" or "const"; value is omitted while the binding is in the temporal dead zone (uninitialized).
"a"{name: [attributes, value]}Any other own data property on the global object that differs from the image's global (overwritten built-ins or non-default attributes), where attributes is the bitmask 1 enumerable | 2 writable | 4 configurable. Omitted when empty.
"d"[name, ...]Names of image global properties deleted by the session. Omitted when empty.
CBOR map keys for ta_tinyscript_read_globals and ta_tinyscript_write_globals.
  • All values use the same structured CBOR value model as slots and tinyscript:host requests.
  • Any binding holding an unserializable value (function other than a script-declared function, Promise, accessor, Symbol, cycle) returns TA_TINYSCRIPT_UNSUPPORTED and writes the offending binding's UTF-8 name into request.refused if provided.
  • On wake, the host runs each script's declare entry point to recreate declared functions and uninitialized lexical slots, then calls ta_tinyscript_write_globals with the saved CBOR map.

Buffer ownership, lifetimes and sizing

tinyscript performs zero implicit heap allocations. Every subsystem — compilation, image preparation, execution stacks, session heaps, CBOR host packets and per-call scratch — runs inside caller-supplied buffers with explicit ownership, disjointness and sizing rules.

BufferSharingOwner and lifetimeSizing and on LIMIT
Compiler workspaceper-compilerCaller owns backing memory; retained by compiler until discarded. Must remain live and exclusive for every ta_tinyscript_check_syntax and ta_tinyscript_compile_with call on that compiler. Serialize calls on one compiler handle. Separate from per-compile scratch and output image buffers.Holds grammar tables and parser engine state (~1–2 MiB reusable across compilations). Returns TA_TINYSCRIPT_LIMIT; retry with a larger buffer.
Compile scratch and output imageper-compileCaller owns both buffers. workspace is transient scratch discarded on return. result.image holds the emitted WebAssembly bytes and is independent after compile returns. workspace, image and compiler workspace must be disjoint.Syntax trees require roughly 94 bytes per source byte during compilation (CLI defaults to 16 MiB workspace; large files need proportionally more). Returns TA_TINYSCRIPT_LIMIT with a diagnostic; retry with a larger buffer.
Prepared module workspaceshared-across-realmsCaller owns both image and workspace; retained by ta_tinyscript_module. Both image bytes and workspace must outlive every realm opened on the prepared module. Read-only after prepare returns. Disjoint from executor and realm workspaces.Holds decoded instructions, register blocks and the shared read-only intrinsic heap (~37 KiB kept, ~80 KiB peak during intrinsic build, plus decoded code). Returns TA_TINYSCRIPT_LIMIT with a diagnostic; retry with a larger workspace.
Executor workspace (and optional allocator)per-host-threadCaller owns workspace; retained by ta_tinyscript_executor until ta_tinyscript_close_executor. One per host thread, shared by every realm that thread runs. Must outlive every realm opened on it; close_executor returns INVALID while any realm remains open. Disjoint from prepared modules, realm workspaces and host packet/scratch buffers.Holds 128 call frames (256 locals each), the value stack and run-loop caches (~333 KiB today; CLI and SCXML adapters pass 384 KiB). Optional ta_tinyscript_allocator (8-byte max alignment) backs growing realm heaps and the LRU runtime compile cache. Returns TA_TINYSCRIPT_LIMIT on open if workspace is too small; compile_cache_bytes = 0 or no allocator disables runtime compilation (UNSUPPORTED).
Realm (session) workspaceper-realmFixed mode: exclusive caller buffer. Growing mode (data == NULL): executor's allocator. Exclusive to one realm from ta_tinyscript_open_realm until ta_tinyscript_close_realm. Fixed buffers are reclaimed by caller after close; growing realms release all blocks to allocator on close. Disjoint from executor, prepared module, other realms, host packet/scratch and per-call scratch buffers.Fixed mode lays out session record, slots and mutable globals at the start, managed heap arena growing upward and object handle table growing downward from the aligned end (capped at TA_HEAP_CEILING = 4 GiB - 4 KiB). Growing mode starts at TA_HEAP_INITIAL (1,024 B) plus session record, grows and packs at safe points up to workspace.capacity (811 to 1,740 B resident at 10,000 sessions). Returns TA_TINYSCRIPT_LIMIT when the heap or ceiling is exhausted; collection via ta_tinyscript_collect may free room.
Host effect packet bufferper-realmCaller owns memory exclusively until replacement or realm close. Holds outgoing CBOR frames for tinyscript:host request(). While status is TA_TINYSCRIPT_EFFECT, outcome.message borrows bytes inside this buffer until ta_tinyscript_reply or the next call into the executor (including collect). Cannot be replaced while EFFECT is pending. Must be non-empty and disjoint from host scratch, the realm workspace and reply message buffers passed to ta_tinyscript_reply.Must fit the largest outgoing structured request frame (CBOR header + method name + argument array). If unset or too small when request() executes, the run stops with TA_TINYSCRIPT_LIMIT.
Host effect scratch bufferper-realmCaller owns memory exclusively until replacement or realm close. Used iteratively during request() CBOR export (cycle bitset + tree-walk frames) and ta_tinyscript_reply CBOR import. Cannot be replaced while EFFECT is pending. Must be non-empty and disjoint from host packet, the realm workspace and reply message buffers.Proportional to nesting depth and active handle count (a few kilobytes covers deep JSON/CBOR trees; 4–64 KiB is typical). Returns TA_TINYSCRIPT_LIMIT on export or reply without corrupting the realm; a failed reply leaves the request pending.
Per-call transient scratch and output buffersper-callCaller owns memory for the duration of the single call. Borrowed only during the C call; immediately reusable on return. Disjoint from the realm workspace and from each other (input message, scratch and output must not overlap).Depends on tree depth or live heap size (collect requires scratch to copy live heap). read_result and read_exception write required byte length into storage.length on LIMIT. Returns TA_TINYSCRIPT_LIMIT leaving the realm and prior results intact; caller retries with a larger buffer without rerunning guest code.
Every buffer across compile, prepare, execution, realms and host messages.
  • Disjointness enforced at boundariesta_tinyscript_set_host_buffers and ta_tinyscript_collect check address ranges and return TA_TINYSCRIPT_INVALID on null, zero-capacity or overlapping buffers.
  • Borrowed outcome.message lifetimeoutcome.message (whether a CBOR effect frame or an UNSUPPORTED reason string) is borrowed only until ta_tinyscript_reply or the next call into the session's executor, ta_tinyscript_collect included. Copy it before switching sessions on the same executor.
  • Atomic CBOR import rollbackFailed ta_tinyscript_write_cbor_slot or ta_tinyscript_reply calls unwind every newly allocated object and handle free-list link, preserving both the existing slot value and the pending request.
  • Zero hidden allocationsEvery byte the library holds comes from a caller buffer or the optional ta_tinyscript_allocator passed to ta_tinyscript_open_executor.

Invocation states and transitions

The host drives execution in a poll-free loop by calling ta_tinyscript_run with an exact instruction fuel budget and reacting to the returned status.

StatusKindMeaningHost action
OKrunningOperation succeeded; realm is ready between calls or ready to run.Invoke an export with ta_tinyscript_call, exchange slots/globals, or start running.
YIELDparkedExact fuel budget expired mid-call; execution state is preserved.Call ta_tinyscript_run again to continue, or start a new between-calls operation to abandon and unwind the stopped call without running guest code.
EFFECTparkedCall parked on an outgoing CBOR request in outcome.message with identifier outcome.request.Read outcome.message, authorize and execute the operation, and deliver the matching CBOR reply via ta_tinyscript_reply, then call ta_tinyscript_run.
SUSPENDEDparkedHost-driven numeric generator yielded a value (outcome.number, outcome.request).Call ta_tinyscript_resume with NEXT, RETURN or THROW and matching request identifier, then call ta_tinyscript_run.
DONEterminalCall returned normally (or run_jobs found no queued promise jobs).Read scalar outcome.number or call ta_tinyscript_read_result / ta_tinyscript_save_result, drain jobs with ta_tinyscript_run_jobs if needed, and call ta_tinyscript_end_job.
THROWNterminalUncaught JavaScript exception unwound the call.Inspect via ta_tinyscript_read_exception or ta_tinyscript_read_result, then call ta_tinyscript_end_job.
TRAPerrorUnrecoverable VM trap or failed module initialization.Do not continue the failed invocation; discard or recreate the realm.
LIMITerrorA caller-supplied buffer, heap ceiling, stack depth or fuel/workspace limit was reached.Retry with a larger buffer where supported (prepare, read_result, read_exception, read_cbor_slot, read_globals, collect) or handle the bounded failure.
INVALIDerrorInvalid arguments, wrong state, overlapping buffers or malformed/stale CBOR frame.Fix the request or discard the bad reply; when returned by ta_tinyscript_reply, the EFFECT remains pending and unchanged.
UNSUPPORTEDerrorFeature or value outside the supported profile (for runtime planned globals, outcome.message carries the UTF-8 feature name).Inspect outcome.message or refused buffer and report the unsupported feature.
All status codes returned by the engine API.
FromCallToRule
OKta_tinyscript_call + ta_tinyscript_runDONECall completes within fuel budget with no pending effects.
OKta_tinyscript_runYIELDFuel reaches zero before the call finishes.
OKta_tinyscript_runEFFECTGuest invokes console.write, clock.now, random.next or tinyscript:host request().
YIELDta_tinyscript_runDONEResumes from the exact paused instruction and finishes.
YIELDta_tinyscript_call (or slot/globals write)OKAbandons the fuel-paused call (unwinding frames without running finally/return) and starts the new operation.
EFFECTta_tinyscript_reply (malformed or stale)EFFECTReturns INVALID; the pending request is not consumed and remains replayable.
EFFECTta_tinyscript_reply (valid value or thrown)YIELDConsumes the request and moves the invocation back to runnable state; the next ta_tinyscript_run resumes execution (or delivers an uncaught thrown reply as THROWN).
EFFECTta_tinyscript_run (before reply)EFFECTReturns EFFECT with 0 instructions consumed and re-exposes the pending request.
EFFECTta_tinyscript_collectEFFECTCollects the parked heap while preserving the pending request and effect buffers.
SUSPENDEDta_tinyscript_resumeYIELDAccepts NEXT/RETURN/THROW for matching requestId so the next ta_tinyscript_run continues.
DONEta_tinyscript_callOKStarts a subsequent export call in the same realm, preserving heap state and slots.
State transitions and non-mutation guarantees.

Independent conformance harnesses

Normative byte-level conformance vectors for both protocol sides. Every hex string is exact definite-length minimal CBOR. Run with tinyscript/protocol/harness.mjs against any engine or host implementation.

The specification currently ships 13 engine vectors, 4 buffer-contract checks and 20 host vectors.

shell
cd tinyscript
mise run protocol

# Test your own host adapter against the normative host vectors
node protocol/harness.mjs --side=host \
  --vectors=build/host-protocol-vectors.json -- <your-host-adapter>

# Test your own engine adapter against the normative engine vectors
node protocol/harness.mjs --side=engine \
  --vectors=build/host-protocol-vectors.json -- <your-engine-adapter>
VectorCategoryChecksOutcome
engine-clock-nowbuiltin-clockDate.now() emits clock.now with empty arguments; engine rejects fractional, out-of-range, stale, trailing-byte and thrown replies without consuming the request, then accepts a valid epoch integer.DONE
engine-random-nextbuiltin-randomMath.random() emits random.next; engine rejects 1.0, negative values, NaN and non-numeric replies, accepts 0.5, and normalizes -0 to +0.DONE
engine-console-writebuiltin-consoleconsole.log emits console.write with binary64 numbers, UTF-8 byte strings and tagged BigInts; engine rejects non-null and thrown replies and accepts [1, id, null].DONE
engine-host-scalarsstructured-valuestinyscript:host request() round-trips safe positive/negative integers, -0, binary64 float, booleans, null, undefined and strings with exact minimal CBOR bytes.DONE
engine-host-bigintsstructured-valuestinyscript:host request() encodes and decodes BigInts using CBOR tags 2 and 3 with minimal big-endian bytes, including 0n (tag 2 empty), -1n (tag 3 empty), 2^64 and -257n.DONE
engine-host-map-utf8structured-valuestinyscript:host request() round-trips plain objects with UTF-8 multi-byte strings (emoji) and rejects malformed replies with duplicate keys, non-minimal heads, invalid UTF-8 or bad frame versions.DONE
engine-host-decode-widthsstructured-valuesStructured replies decode CBOR float16 (0xf9), float32 (0xfa) and unsigned integers above 2^53 - 1 (as BigInt).DONE
engine-thrown-builtin-errorerror-repliesA thrown reply [2, id, {"name": "TypeError", "message": "no such queue"}] throws a catchable TypeError instance with non-enumerable message.DONE
engine-thrown-custom-errorerror-repliesA thrown reply with an unknown error name creates an Error instance keeping its custom name, non-enumerable message and extra own properties.DONE
engine-thrown-raw-uncaughterror-repliesA thrown reply carrying a non-map value ("boom") throws that value verbatim; if uncaught, the invocation finishes with THROWN.THROWN
engine-monotonic-idslifecycleSequential host requests in one invocation increment requestId monotonically (1, 2, 3).DONE
engine-guest-invalid-requestvalidationInvalid guest arguments to request() (empty method name, non-array args, function or cycle inside args) throw a guest TypeError without emitting any host effect.DONE
engine-missing-host-buffersbuffersCalling tinyscript:host request() on a realm without ta_tinyscript_set_host_buffers stops with TA_TINYSCRIPT_LIMIT.LIMIT
Engine-side conformance vectors in tinyscript/spec/host-protocol.xml.
VectorCategoryAcceptChecks
host-clock-nowbuiltin-clockacceptHost handles clock.now request and replies with [1, 1, integral epoch ms in Date range].
host-random-nextbuiltin-randomacceptHost handles random.next request and replies with [1, 1, number in [0, 1)].
host-console-numberbuiltin-consoleacceptHost handles console.write with binary64 number and replies [1, 1, null].
host-console-bytesbuiltin-consoleacceptHost handles console.write with UTF-8 major 2 byte string and replies [1, 1, null].
host-console-bigintbuiltin-consoleacceptHost handles console.write with tag 2 BigInt and replies [1, 1, null].
host-echo-scalarsstructured-valuesacceptHost echoes scalar mix preserving -0 as binary64, safe ints as minimal integers, booleans, null, undefined and UTF-8 strings.
host-echo-bigintsstructured-valuesacceptHost echoes tag 2 and tag 3 BigInts using minimal big-endian bytes without collapsing them to CBOR integers.
host-echo-map-utf8structured-valuesacceptHost echoes a plain object with UTF-8 keys and multi-byte emoji string.
host-unknown-method-throwserror-repliesacceptHost refuses an unauthorized or unknown method with a valid thrown reply [2, 7, {"name": ..., "message": ...}].
host-reject-emptymalformed-requestsrejectHost rejects an empty byte buffer.
host-reject-zero-idmalformed-requestsrejectHost rejects a request with requestId = 0.
host-reject-bad-versionmalformed-requestsrejectHost rejects a request with version != 1.
host-reject-wrong-aritymalformed-requestsrejectHost rejects a 3-element request array.
host-reject-non-text-methodmalformed-requestsrejectHost rejects a request whose method field is not a UTF-8 text string.
host-reject-non-array-argsmalformed-requestsrejectHost rejects a request whose arguments field is not an array.
host-reject-trailing-bytemalformed-requestsrejectHost rejects a request with a trailing byte after the root array.
host-reject-non-minimal-idmalformed-requestsrejectHost rejects non-minimal CBOR integer encoding (0x18 0x01 for 1).
host-reject-indefinite-arraymalformed-requestsrejectHost rejects indefinite-length CBOR array (0x9f ... 0xff).
host-reject-duplicate-map-keymalformed-requestsrejectHost rejects a request argument map containing duplicate keys.
host-reject-invalid-utf8malformed-requestsrejectHost rejects a request containing invalid UTF-8 bytes in a text string.
Host-side conformance vectors in tinyscript/spec/host-protocol.xml.

Read v1 XML specRead harness guideRead embedding guide

Planned redesign before fetch (reversioned to v1)

Positional CBOR host protocol with API-level versioning, one-way notifications, pipelined async requests, binary Uint8Array payloads and branded DOMException errors. Built in packet p2-host-protocol before fetch lands, then reversioned to version 1.

Every frame starts with a pure frame-kind tag: 0 sync request, 1 async request, 2 value reply, 3 thrown reply, or 4 notification. Protocol version is queried once via ta_tinyscript_host_protocol_version() and is never placed in slot 0.

JSON-RPC 2.0 over CBOR maps was rejected because tinyscript's host boundary is a hot per-effect path. Positional arrays validate kind and id in 3 bytes before heap allocation and avoid map key-order ambiguity. Wire frames stay 2.6x to 3.6x smaller, JS and WebIDL errors map directly, and non-JSON CBOR types stay honest.

API-level versioning (ta_tinyscript_host_protocol_version()): Hosts query ta_tinyscript_host_protocol_version() once at startup to verify wire compatibility. During p2-host-protocol this draft is tracked as v2 alongside v1. Once p2-host-protocol lands, the spec reversions to version 1 as the sole public protocol.

FrameDirectionSyntaxMeaning
Sync request frameengine-to-host[0, requestId, method, arguments]Emitted when a call stops with TA_TINYSCRIPT_EFFECT for a blocking synchronous operation (clock.now, random.next, or tinyscript:host request()). Both wire slot 1 and outcome.request carry requestId. The VM stays parked until the host answers requestId with frame kind 2 (value reply) or 3 (thrown reply).
Async pipelined request frameengine-to-host[1, requestId, method, arguments]Emitted by tinyscript:host requestAsync(method, args) with status TA_TINYSCRIPT_NOTIFY (or non-blocking emit). The engine immediately allocates and returns a pending Promise rooted in pending_requests, sets outcome.request = requestId, and resumes execution on the next ta_tinyscript_run without waiting for a reply. Multiple async requests may be in flight concurrently and settled in any order via ta_tinyscript_reply between calls (or while parked) using frame kind 2 (fulfill) or 3 (reject).
Value reply framehost-to-engine[2, requestId, result]Delivered via ta_tinyscript_reply to resume a parked blocking sync request (returning result) or settle an in-flight async request (fulfilling its Promise and enqueuing reaction jobs for ta_tinyscript_run_jobs). Invalid, stale, duplicate or malformed replies return INVALID without mutating state.
Thrown / rejected reply framehost-to-engine[3, requestId, error]Valid for tinyscript:host sync request() (throws error synchronously at the call site) and requestAsync() (rejects the pending Promise with error). Refused with INVALID on built-in scalar methods (clock.now, random.next).
One-way notification frameengine-to-host[4, method, arguments]Emitted with status TA_TINYSCRIPT_NOTIFY and outcome.request = 0 for fire-and-forget host actions (console.write, timer.cancel, request.cancel, tinyscript:host notify()). Carries no requestId and expects no reply: the host reads or copies outcome.message and resumes immediately with ta_tinyscript_run. Calling ta_tinyscript_reply during TA_TINYSCRIPT_NOTIFY returns INVALID.
Target positional CBOR frames in tinyscript/spec/host-protocol-v2.xml (slot 0 is a pure frame-kind tag 0..4; reversioned to v1 on landing packet p2-host-protocol).
MethodModeArgumentsResult
console.writenotification[number | bigint | bytes]none (one-way notification)
clock.nowrequest[]number (integral epoch milliseconds)
random.nextrequest[]number in [0, 1)
tinyscript:host request(method, args)request[...structured CBOR values including Uint8Array]any structured CBOR value, or thrown Error/DOMException
tinyscript:host requestAsync(method, args)async-request[...structured CBOR values including Uint8Array]Promise settled by later [2, id, value] or [3, id, error]
tinyscript:host notify(method, args)notification[...structured CBOR values including Uint8Array]undefined (one-way notification)
Target method modes in tinyscript/spec/host-protocol-v2.xml (8 engine vectors, 22 host vectors, 6 buffer checks).

Read v2 target XML spec