Skip to content

Runtime Control & Objects

JavaScript/TypeScript Preview 4 APIs expose runtime-control and object-reference codecs plus typed runtime events. WebSocket packet framing remains inside the WebSocket provider and is not a public application helper.

Runtime-neutral helpers live in @nnrp/core. Browser packages may call the WASM-backed helpers from @nnrp/browser-client; backend packages may call native-backed helpers through role and transport packages. Transport packages own their transport behavior; they are not configuration flags over a hidden implementation.

Import

ts
import {
  decodeCacheInvalidateMetadata,
  decodeFlowUpdateMetadata,
  decodeFrameSubmitMetadata,
  decodeResultHintMetadata,
  decodeRuntimeControlMetadata,
  decodeRuntimeObjectMetadata,
  encodeCacheInvalidateMetadata,
  encodeFlowUpdateMetadata,
  encodeFrameSubmitMetadata,
  encodeResultHintMetadata,
  encodeRuntimeControlMetadata,
  encodeRuntimeObjectMetadata,
  encodeRuntimeObjectMetadataSegments,
  NnrpMessageType,
} from "@nnrp/core";

Baseline Metadata Codecs

@nnrp/core exposes exact-width codecs for every frozen NNRP/1 baseline metadata type used by the Preview 4 role API and public Conformance suite. Each encoder accepts the named metadata type and returns Uint8Array; each decoder accepts Uint8Array and returns that same metadata type. Decoders reject incorrect widths, non-zero reserved fields, invalid enum values, and invalid flag combinations.

Metadata typeEncoderDecoder
ClientHelloMetadataencodeClientHelloMetadatadecodeClientHelloMetadata
SessionPatchAckMetadataencodeSessionPatchAckMetadatadecodeSessionPatchAckMetadata
FlowUpdateMetadataencodeFlowUpdateMetadatadecodeFlowUpdateMetadata
ResultHintMetadataencodeResultHintMetadatadecodeResultHintMetadata
FrameSubmitMetadataencodeFrameSubmitMetadatadecodeFrameSubmitMetadata
ResultPushMetadataencodeResultPushMetadatadecodeResultPushMetadata
CachePutMetadataencodeCachePutMetadatadecodeCachePutMetadata
CacheAckMetadataencodeCacheAckMetadatadecodeCacheAckMetadata
CacheInvalidateMetadataencodeCacheInvalidateMetadatadecodeCacheInvalidateMetadata
TransportProbeMetadataencodeTransportProbeMetadatadecodeTransportProbeMetadata
TransportProbeAckMetadataencodeTransportProbeAckMetadatadecodeTransportProbeAckMetadata
ObjectReferenceBlockencodeObjectReferenceBlockdecodeObjectReferenceBlock

The packet-level Conformance cases compose these metadata codecs with the common-header framing owned by the native or WASM runtime. They do not define a second JavaScript wire implementation.

encodeRuntimeControlMetadata

Encodes one Preview 4 control metadata object.

ParameterTypeRequiredDescription
messageTypeNnrpMessageTypeYesOne of the Preview 4 control message types.
metadataRuntime control metadataYesMetadata object matching messageType.
tailUint8ArrayNoExtension bytes, diagnostic bytes, progress body, or partial-result body declared by metadata.
Returns
Uint8Array
ts
const payload = encodeRuntimeControlMetadata(NnrpMessageType.Progress, {
  operationId: 42n,
  progressSequence: 1n,
  stageCode: 2,
  percentX100: 2500,
  objectId: 0n,
  bodyBytes: 0,
});

decodeRuntimeControlMetadata

Decodes one control metadata payload.

ParameterTypeRequiredDescription
messageTypeNnrpMessageTypeYesMessage type that selected the metadata layout.
payloadUint8ArrayYesMetadata bytes plus the declared tail.
Returns
DecodedRuntimeControlMetadata

DecodedRuntimeControlMetadata has two readonly fields:

FieldTypeDescription
metadataRuntimeControlMetadataMetadata object selected by messageType.
tailUint8ArrayOwned copy of the declared diagnostic, body, or extension payload.

encodeRuntimeObjectMetadata

Encodes object, object-reference, object-delta, cache-reference, and cache-miss metadata.

ParameterTypeRequiredDescription
messageTypeNnrpMessageTypeYesOne of ObjectDeclare, ObjectRef, ObjectRelease, ObjectPatch, ObjectDelta, CacheReference, or CacheMiss.
metadataRuntime object metadataYesMetadata object matching messageType.
tailUint8ArrayNoExtension bytes, diagnostics, or delta payload declared by metadata.
Returns
Uint8Array

encodeRuntimeObjectMetadataSegments

Encodes runtime object metadata and ordered tail segments directly into one owned payload. This helper avoids an intermediate concatenated buffer when object metadata and a large delta are supplied separately.

ParameterTypeRequiredDescription
messageTypeNnrpMessageTypeYesAny runtime object or cache message type accepted by encodeRuntimeObjectMetadata.
metadataRuntime object metadataYesMetadata matching messageType; declared tail lengths apply to the sum of all segments.
tailSegmentsreadonly Uint8Array[]YesTail segments in exact wire order, copied directly into the returned owned payload.
Returns
Uint8Array

For ObjectPatch and ObjectDelta, pass [metadataBody, delta]. Segment order remains semantic when either segment is empty.

decodeRuntimeObjectMetadata

Decodes one runtime object or cache metadata payload.

ParameterTypeRequiredDescription
messageTypeNnrpMessageTypeYesMessage type that selected the metadata layout.
payloadUint8ArrayYesMetadata bytes plus the declared tail.
Returns
DecodedRuntimeObjectMetadata

Baseline Cache Invalidation

Preview4 reuses the existing CacheInvalidate NNRP/1 frame instead of defining a second runtime invalidation message.

APIParametersReturns
encodeCacheInvalidateMetadataCacheInvalidateMetadataUint8Array
decodeCacheInvalidateMetadataUint8ArrayCacheInvalidateMetadata

CacheInvalidateMetadata has the frozen fields invalidateScope, cacheNamespace, cacheKeyHi, cacheKeyLo, and reasonCode. cacheNamespace is a number; both key words are bigint. CachePutMetadata, CacheAckMetadata, and ObjectReferenceBlock use the same identity widths.

Local Cache Lease State

CacheLease is the validated TypeScript value for a granted lease. It is not a wire payload or a native/WASM handle.

TypeScript fieldTypeProtocol field
objectIdCacheObjectIdobject_id
objectVersionbigintobject_version
leaseIdbigintlease_id
ownerScopeCacheLeaseOwnerScopeowner_scope
ownerIdbigintowner_id
grantedAtMillisbigintgranted_at_ms
ttlMillisnumber (u32)ttl_ms

CacheObjectId contains cacheNamespace: number (u32), cacheKeyHi: bigint, cacheKeyLo: bigint, and objectKind: NnrpCacheObjectKind (u32). CacheLeaseOwnerScope is Connection = 0, Session = 1, or Operation = 2. Use expiresAtMillis, isExpiredAt, and validateVersion for local validation.

High-Level Runtime Frame Contract

Applications send Preview4 controls, runtime objects, and cache frames through client or server session methods. They do not construct a native request, select an ABI symbol, or concatenate a metadata buffer manually. Every session method performs exactly one coarse runtime call after the SDK validates and encodes its typed arguments.

The internal native/WASM binding method is frozen as:

ts
sendRuntimeFrame(request: NnrpRuntimeFrameSendRequest): void | Promise<void>;

NnrpRuntimeFrameSendRequest has the readonly fields sessionOptions, messageType, frameId, and payload. payload is the complete encoded metadata and declared tail. It is an internal binding contract; public applications use the named session methods documented on the client and server pages.

NnrpRuntimeEvent

Every incoming role event is decoded into one envelope with a complete wire header and two closed tagged unions. Applications discriminate event.metadata.type and event.tail.type; the removed flat NnrpRuntimeFrameEvent.type surface is not part of Preview4.

ts
interface NnrpRuntimeEvent {
  readonly header: NnrpRuntimeFrameHeader;
  readonly metadata: NnrpRuntimeEventMetadata;
  readonly tail: NnrpRuntimeEventTail;
}

NnrpRuntimeEventMetadata and NnrpRuntimeEventTail are closed tagged unions. The exhaustive table below selects exactly one variant of each union from header.messageType.

NnrpRuntimeFrameHeader preserves versionMajor, wireFormat, messageType, flags, sessionId, frameId, viewId, routeId, and traceId. A local lifecycle notification has no wire header and therefore remains NnrpOperationLifecycleEvent; the SDK never fabricates a zero-filled header.

The mapping below is exhaustive. The message type selects one metadata variant and one semantic tail variant before the event reaches application code.

Messagesmetadata.typeMetadata valuetail.type
SessionClosesession_closeNnrpSessionCloseMetadatanone
FrameSubmitframe_submitNnrpFrameSubmitMetadatabody
FrameCancel, ResultDropnonenonenone
ResultPushresult_pushNnrpResultPushMetadatabody
ResultHintresult_hintNnrpResultHintMetadatanone
FlowUpdateflow_updateNnrpFlowUpdateMetadatanone
Cancel, Abortcontrol_requestControlRequestMetadatadiagnostic
PriorityUpdate, Deadline, ExpireAtschedulingSchedulingMetadatanone
SupersedesupersedeSupersedeMetadatadiagnostic
BudgetUpdatebudgetBudgetMetadatanone
ProgressprogressProgressMetadatabody
PartialResultpartial_resultPartialResultMetadatabody
Backpressure, CreditUpdatepressurePressureMetadatanone
CapabilityNegotiation, DegradeProfilecapabilityCapabilityMetadatabody
RouteHint, ExecutionHintroute_hintRouteHintMetadatabody
TraceContexttrace_contextTraceContextMetadatabody
ResultDropReasonresult_drop_reasonResultDropReasonMetadatadiagnostic
ErrorRecoverablerecoverable_errorRecoverableErrorMetadatadiagnostic
RetryAfterretry_afterRetryAfterMetadatadiagnostic
ObjectDeclareobject_descriptorObjectDescriptorMetadatabody
ObjectRefobject_referenceObjectReferenceMetadatabody
ObjectReleaseobject_releaseObjectReleaseMetadatadiagnostic
ObjectPatch, ObjectDeltaobject_deltaObjectDeltaMetadatametadata_body_and_delta
CacheReferencecache_referenceCacheReferenceMetadatabody
CacheMisscache_missCacheMissMetadatadiagnostic
CacheInvalidatecache_invalidateCacheInvalidateMetadatanone

Tail variants own their bytes: body contains body, diagnostic contains diagnostic, and metadata_body_and_delta contains separate metadataBody and delta buffers. Malformed declared lengths fail before delivery. Handshake replies, probe replies, migration acknowledgements, cache command acknowledgements, ping/pong, connection close, and fatal connection errors are consumed by their dedicated APIs rather than being reclassified as runtime events.

Runtime Control Metadata

NnrpMessageType

Preview 4 adds these message members to the JavaScript enum:

Cancel, Abort, PriorityUpdate, Deadline, ExpireAt, Supersede, BudgetUpdate, Progress, PartialResult, Backpressure, CreditUpdate, CapabilityNegotiation, DegradeProfile, RouteHint, ExecutionHint, TraceContext, ResultDropReason, ObjectDeclare, ObjectRef, ObjectRelease, ObjectPatch, ObjectDelta, CacheReference, CacheMiss, CacheInvalidate, ErrorRecoverable, RetryAfter.

TypeScript Numeric Mapping

Wire fields declared as u64 use bigint in the JavaScript API. Wire fields declared as u32, u16, u8, or i16 use number and are rejected when they are not integers or exceed the frozen wire range. Enum-valued fields use the corresponding numeric TypeScript enum. Encoders snapshot the optional tail; decoders return an owned Uint8Array rather than a view into caller-owned storage. ProgressMetadata.percentX100 accepts 0..10000 and the frozen 0xffff unknown-value sentinel.

RuntimeControlMetadata is the union of every metadata interface in the control metadata field map below. A metadata object is valid only for the message types listed in its row.

Control Metadata Field Map

TypeMessage typesFrozen fields
ControlRequestMetadataCancel, AbortoperationId, controlSequence, reasonCode, sourceRole, flags, diagnosticBytes
SchedulingMetadataPriorityUpdate, Deadline, ExpireAtoperationId, controlSequence, priorityClass, priorityDelta, deadlineUnixMs, flags
SupersedeMetadataSupersedeoldOperationId, newOperationId, controlSequence, dropReasonCode, flags, diagnosticBytes
BudgetMetadataBudgetUpdateoperationId, computeBudgetUnits, memoryBudgetBytes, bandwidthBudgetBytes, tokenBudget, flags
ProgressMetadataProgressoperationId, progressSequence, stageCode, percentX100, objectId, bodyBytes
PartialResultMetadataPartialResultoperationId, resultSequence, objectId, deltaSequence, bodyBytes, flags
PressureMetadataBackpressure, CreditUpdatescopeId, creditWindow, pressureLevel, pressureReason, retryAfterMs, flags
CapabilityMetadataCapabilityNegotiation, DegradeProfileprofileId, capabilityCount, costModelId, preferenceRank, limitBytes, limitUnits, bodyBytes, flags
RouteHintMetadataRouteHint, ExecutionHintoperationId, routeId, executorClass, affinityClass, deadlineUnixMs, bodyBytes, flags
TraceContextMetadataTraceContexttraceId, spanId, parentSpanId, stageCode, flags, bodyBytes
ResultDropReasonMetadataResultDropReasonoperationId, resultSequence, dropReasonCode, sourceRole, flags, diagnosticBytes
RecoverableErrorMetadataErrorRecoverableerrorCode, errorScope, recoveryAction, sourceRole, flags, retryAfterMs, relatedSessionId, relatedFrameId, relatedViewId, diagnosticBytes
RetryAfterMetadataRetryAfterscopeId, controlSequence, retryAfterMs, jitterMs, reasonCode, sourceRole, flags, diagnosticBytes

Runtime Object Metadata

TypeMessage typesFrozen fields
ObjectDescriptorMetadataObjectDeclareobjectId, objectKind, producerRole, consumerRole, sessionId, byteSize, computeCostUnits, memoryLocationHint, ownershipHint, lifetimeHintMs, metadataBytes
ObjectReferenceMetadataObjectRefobjectId, operationId, objectVersion, offset, length, flags, metadataBytes
ObjectReleaseMetadataObjectReleaseobjectId, operationId, releaseReason, sourceRole, flags, diagnosticBytes
ObjectDeltaMetadataObjectPatch, ObjectDeltaobjectId, deltaSequence, regionOffset, regionBytes, deltaBytes, flags, metadataBytes
CacheReferenceMetadataCacheReferencecacheNamespace, cacheKeyHi, cacheKeyLo, profileId, reuseScope, leaseId, producerTraceId, expirationHintMs, metadataBytes, flags
CacheMissMetadataCacheMisscacheNamespace, cacheKeyHi, cacheKeyLo, missReason, profileId, diagnosticBytes

Runtime Enums

EnumMembers
RuntimeObjectKindUnspecified, Tensor, TokenBlock, ImageTile, FeatureMap, ToolResult, TraceSegment, OpaqueBytes, DocumentChunk, AudioChunk, VideoChunk, RoutePlan, CacheManifest
RuntimeRoleUnspecified, Client, Server, Runtime, Subagent, Tool, Scheduler, ConformanceRunner
ErrorScopeConnection, Session, Frame
MemoryLocationHintUnspecified, HostMemory, DeviceMemory, SharedMemory, RemoteMemory, MmapFile, ObjectStore
OwnershipHintUnspecified, ProducerOwned, ConsumerOwned, SessionOwned, Borrowed, TransferOnRef, ReleaseOnDrop
ObjectReleaseReasonCompleted, Cancelled, Expired, Replaced, Invalidated, OwnerClosed, LeaseExpired, ConformanceInjection
CacheReuseScopeOperation, Session, Connection, Global, Tenant, Profile
CacheMissReasonUnknown, NotFound, Expired, Invalidated, SchemaMismatch, ProducerUnavailable, LeaseRequired, PermissionDenied

NNRP Documentation