Skip to content

Runtime Control & Objects

JavaScript/TypeScript Preview 4 APIs freeze the runtime-control, object-reference, and WebSocket binary-frame helpers that SDK packages must expose. The names below are the public API contract for NNRP/1 JavaScript packages.

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,
  decodeRuntimeControlMetadata,
  decodeRuntimeObjectMetadata,
  decodeWebSocketBinaryFrame,
  decodeWebSocketBinaryFrameBatch,
  encodeCacheInvalidateMetadata,
  encodeRuntimeControlMetadata,
  encodeRuntimeObjectMetadata,
  encodeWebSocketBinaryFrame,
  NnrpMessageType,
} from "@nnrp/core";

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

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. CacheLease is local validated state with objectId, objectVersion, leaseId, ownerScope, ownerId, grantedAtMillis, and ttlMillis.

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.

Typed Runtime Frame Events

Incoming Preview4 frames are decoded before they reach application code. Each event contains type, messageType, metadata, sessionId, and the semantic tail field from this table. Tail buffers are owned Uint8Array snapshots. A no-tail event omits the tail field.

Event typeMessageMetadataSemantic tail field
cancel, abortCancel, AbortControlRequestMetadatadiagnostic
priority-update, deadline, expire-atmatching scheduling messageSchedulingMetadatanone
supersedeSupersedeSupersedeMetadatadiagnostic
budget-updateBudgetUpdateBudgetMetadatanone
progressProgressProgressMetadatabody
partial-resultPartialResultPartialResultMetadatabody
backpressure, credit-updatematching pressure messagePressureMetadatanone
capability-negotiation, degrade-profilematching capability messageCapabilityMetadatabody
route-hint, execution-hintmatching routing messageRouteHintMetadatabody
trace-contextTraceContextTraceContextMetadatabody
result-drop-reasonResultDropReasonResultDropReasonMetadatadiagnostic
recoverable-errorErrorRecoverableRecoverableErrorMetadatadiagnostic
retry-afterRetryAfterRetryAfterMetadatadiagnostic
object-declareObjectDeclareObjectDescriptorMetadatabody
object-refObjectRefObjectReferenceMetadatabody
object-releaseObjectReleaseObjectReleaseMetadatadiagnostic
object-patch, object-deltamatching object update messageObjectDeltaMetadatametadataBody, delta
cache-referenceCacheReferenceCacheReferenceMetadatabody
cache-missCacheMissCacheMissMetadatadiagnostic
cache-invalidateCacheInvalidateCacheInvalidateMetadatanone

For object patch and delta events, the SDK splits the wire tail at metadata.metadataBytes; the remaining metadata.deltaBytes bytes become delta. A malformed length fails before an event is delivered. Existing submit, result, lifecycle, and migration event variants remain separate from this runtime-frame union.

encodeWebSocketBinaryFrame

Builds the binary frame used by the WebSocket transport.

ParameterTypeRequiredDescription
headerNnrpRuntimeFrameHeaderYesHeader fields except metadataLength and bodyLength; the helper derives both lengths from the buffers.
metadataUint8ArrayNoMetadata payload.
bodyUint8ArrayNoBody payload.
Returns
Uint8Array

decodeWebSocketBinaryFrame

Splits one WebSocket binary frame into header, metadata view, and body view.

ParameterTypeRequiredDescription
frameUint8ArrayYesOne complete WebSocket binary message.
Returns
DecodedRuntimeFrame

decodeWebSocketBinaryFrameBatch

Decodes concatenated binary frames from local buffers and conformance fixtures.

ParameterTypeRequiredDescription
batchUint8ArrayYesConcatenated frames.
options{ limit?: number }NoMaximum decoded frames; 0 or omitted means no limit.
Returns
DecodedRuntimeFrame[]

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
CacheReferenceMetadataCacheReferencecacheKeyHi, cacheKeyLo, profileId, reuseScope, leaseId, producerTraceId, expirationHintMs, metadataBytes, flags
CacheMissMetadataCacheMisscacheKeyHi, 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

NnrpRuntimeFrameHeader

FieldTypeDescription
messageTypeNnrpMessageTypeFrame message type.
flagsnumberHeader flags.
sessionIdnumberSession id.
generationnumberSession generation.
frameIdnumberFrame id.

NNRP Documentation