Skip to content

JavaScript/TypeScript Client API

Client code starts from the same lifecycle shape in native and browser hosts:

  1. Open a runtime.
  2. Connect a client endpoint.
  3. Open a session.
  4. Submit, cancel, or poll events.

The package names differ by host, but the client session methods intentionally stay aligned.

HostRole packageTransport packages
Node.js/Deno@nnrp/native-clientTCP, QUIC, IPC, and WebSocket carrier packages
Browser/edge@nnrp/browser-client@nnrp/transport-websocket

openNativeClient

Opens a native client in Node.js or Deno.

ParameterTypeRequiredDescription
optionsNnrpNativeClientOptionsYesEndpoint, transport policy, installed transport providers, session defaults, and optional FFI binding.
ReturnsThrows
Promise<NnrpClient>NnrpCapabilityError or NnrpNativeBindingUnavailableError.
ts
import { openNativeClient } from "@nnrp/native-client";
import { createTcpTransportProvider } from "@nnrp/transport-tcp";
import { createQuicTransportProvider } from "@nnrp/transport-quic";

const client = await openNativeClient({
  endpoint: "nnrps://runtime.example/session/default",
  providerRoutes: {
    quic: {
      security: { mode: "client", serverName: "runtime.example", trustedCertificateDer },
    },
    tcp: {
      security: { mode: "client", serverName: "runtime.example", trustedCertificateDer },
    },
  },
  transportPolicy: "auto",
  transports: [
    createQuicTransportProvider(),
    createTcpTransportProvider(),
  ],
});

openBrowserRuntime

Opens a browser runtime. Browser clients connect from this runtime rather than directly from a native endpoint because the browser has a separate WASM/module lifecycle.

ParameterTypeRequiredDescription
optionsNnrpBrowserRuntimeOptionsNoModule URL, precompiled module, artifact manifest, transport policy, and browser transport providers.
Returns
Promise<NnrpBrowserRuntime>
ts
import { openBrowserRuntime } from "@nnrp/browser-client";
import { createWebSocketTransportProvider } from "@nnrp/transport-websocket";

const runtime = await openBrowserRuntime({
  transportProviders: [createWebSocketTransportProvider()],
});

NnrpBrowserRuntime.connect

Creates a browser client from an opened browser runtime.

ParameterTypeRequiredDescription
optionsNnrpBrowserConnectOptionsYesEndpoint, optional transport policy, optional transport providers, and optional session defaults.
Returns
NnrpBrowserClient
ts
const client = runtime.connect({
  endpoint: "nnrps://runtime.example/session/default",
  providerRoutes: {
    websocket: { endpoint: "wss://runtime.example/nnrp" },
  },
  transportPolicy: "auto",
});

NnrpClient.openSession

Opens a client session. Native and browser clients expose the same session concept.

ParameterTypeRequiredDescription
optionsNnrpSessionOptions or NnrpBrowserSessionOptionsNoTransport-neutral SESSION_OPEN intent and local recovery capacity.
Returns
Promise<NnrpClientSession> or Promise<NnrpBrowserClientSession>
ts
const session = await client.openSession({ profileId: 1 });

openSession completes only after the runtime has finished the automatic connection handshake and received SESSION_OPEN_ACK. It does not return a lazy session wrapper.

NnrpClient.resumeSession

Resumes one runtime-issued session on the existing logical client connection. Native and browser clients expose the same asynchronous operation.

ParameterTypeRequiredDescription
ticketNnrpSessionRecoveryTicketYesOpaque canonical NRTK ticket issued by runtime.
optionsNnrpSessionOptions or NnrpBrowserSessionOptionsNoOptional overrides for the resumed session open.
Returns
Promise<NnrpClientSession> or Promise<NnrpBrowserClientSession>

Invalid, expired, truncated, or unknown tickets reject. They never fall back to a fresh session.

Client Lifecycle Methods

These methods have the same shape on NnrpClient and NnrpBrowserClient.

MethodParametersReturnsDescription
nextSessionEvent(sessionId, options?)sessionId: number, options?: NnrpEventPollOptionsPromise<NnrpClientEvent>Reads the next event for one negotiated session.
close()NonePromise<void>Closes owned sessions, the role connection, and the runtime.

ClientSession.submit

Submits a request and waits for a result. Native clients use the native submit/result hot path; browser clients use the browser runtime path, but the request shape is shared.

ParameterTypeRequiredDescription
requestNnrpSubmitRequestYesNon-zero operation id, independent frame id, payload/tensors, profile, cache/schema metadata, and submit mode.
Returns
Promise<NnrpResult>
ts
const result = await session.submit({
  operationId: 1n,
  frameId: 1,
  payload: new Uint8Array([1, 2, 3]),
  inputProfile: "tensor",
  submitMode: "inline",
});

ClientSession.submitNoWait

Submits a request and returns the operation id. Native and browser client sessions both expose this method.

ParameterTypeRequiredDescription
requestNnrpSubmitRequestYesSubmit request.
Returns
Promise<bigint>

ClientSession.cancel

Sends a Preview4 CANCEL frame. NnrpClientSession and NnrpBrowserClientSession expose the same method.

ParameterTypeRequiredDescription
metadataControlRequestMetadataYesFrozen operation id, sequence, reason, role, flags, and diagnostic length.
diagnosticUint8ArrayNoBytes whose length equals metadata.diagnosticBytes.
Returns
Promise<void>

Preview4 Client Control Methods

The native and browser session classes expose the same control surface. Every method encodes the named NNRP message and submits it through the active runtime in one coarse runtime call.

MethodMessageMetadataOptional tail
abort(metadata, diagnostic?)AbortControlRequestMetadatadiagnostic bytes
updatePriority(metadata)PriorityUpdateSchedulingMetadatanone
updateDeadline(metadata)DeadlineSchedulingMetadatanone
expireAt(metadata)ExpireAtSchedulingMetadatanone
supersede(metadata, diagnostic?)SupersedeSupersedeMetadatadiagnostic bytes
updateBudget(metadata)BudgetUpdateBudgetMetadatanone
negotiateCapabilities(metadata, body?)CapabilityNegotiationCapabilityMetadatacapability entries
degradeProfile(metadata, body?)DegradeProfileCapabilityMetadatacapability entries
sendRouteHint(metadata, body?)RouteHintRouteHintMetadatatyped hint body
sendExecutionHint(metadata, body?)ExecutionHintRouteHintMetadatatyped hint body
sendTraceContext(metadata, body?, operationId?)TraceContextTraceContextMetadatatrace attributes; omitted operation is session scope
sendControl(messageType, metadata, tail?)Any client-sendable Preview4 control frameMatching runtime metadata typedeclared tail

sendControl is the typed escape hatch for ErrorRecoverable, RetryAfter, and extension-safe control routing. It rejects a metadata type that does not match messageType.

Preview4 Client Object And Cache Methods

MethodMessageMetadataOptional tail
declareObject(metadata, body?)ObjectDeclareObjectDescriptorMetadataobject metadata
referenceObject(metadata, body?)ObjectRefObjectReferenceMetadatareference metadata
releaseObject(metadata, diagnostic?)ObjectReleaseObjectReleaseMetadatadiagnostic bytes
patchObject(metadata, delta, metadataBody?)ObjectPatchObjectDeltaMetadatametadata body, then delta
sendObjectDelta(metadata, delta, metadataBody?)ObjectDeltaObjectDeltaMetadatametadata body, then delta
referenceCache(metadata, body?)CacheReferenceCacheReferenceMetadatacache metadata
reportCacheMiss(metadata, diagnostic?)CacheMissCacheMissMetadatadiagnostic bytes
invalidateCache(metadata)CacheInvalidateCacheInvalidateMetadatanone

For object patch and delta methods, metadataBody.byteLength must equal metadata.metadataBytes and delta.byteLength must equal metadata.deltaBytes. The wire tail is the metadata body followed by the delta bytes. Object and cache methods return Promise<void>. They do not perform an implicit cache lookup before each submit.

Preview4 Runtime Events

The runtime variant returned by nextEvent() and events() supports every Preview4 runtime-frame discriminant: cancel, abort, priority-update, deadline, expire-at, supersede, budget-update, progress, partial-result, backpressure, credit-update, capability-negotiation, degrade-profile, route-hint, execution-hint, trace-context, result-drop-reason, recoverable-error, retry-after, object-declare, object-ref, object-release, object-patch, object-delta, cache-reference, cache-miss, and cache-invalidate. The exact typed fields and semantic tail names are frozen in Runtime Control & Objects.

Events preserve wire order within one operation. Events from different operations may interleave. After cancellation, result-drop-reason remains observable, while late result and partial-result payloads for the cancelled operation are suppressed from normal result iteration.

Submit Cancellation

submit(request, options?) and submitNoWait(request, options?) accept NnrpSubmitOptions:

FieldTypeRequiredDescription
signalNnrpAbortSignalLikeNoAn already-aborted signal rejects before dispatch; an abort after dispatch sends CANCEL.
timeoutMillisnumberNoLocal wait bound. The SDK sends DEADLINE before dispatch and cancels work when the bound expires.

These helpers use the same control sequence allocator as explicit control methods; they do not invent an out-of-band cancellation channel.

Cancellation of an already-dispatched submit() deterministically rejects that submit wait with NnrpTimeoutError, whose diagnostic.code is NNRP_SUBMIT_CANCELLED, after initiating CANCEL. Expiry rejects it with the same error class and the NNRP_SUBMIT_TIMEOUT diagnostic code after initiating CANCEL; the pre-dispatch DEADLINE remains part of the wire flow. In both cases, the local terminal lifecycle event remains available from nextEvent() and must not race the same submit() into a resolved NnrpResult. A terminal lifecycle initiated independently by the peer may still resolve submit() as non-success NnrpResult evidence.

ClientSession.nextEvent

Reads the next client event. NnrpClientEvent is a closed tagged union with a runtimeNnrpRuntimeEvent variant and a lifecycle NnrpOperationLifecycleEvent variant.

ParameterTypeRequiredDescription
optionsNnrpEventPollOptionsNoEvent polling options.
Returns
Promise<NnrpClientEvent>

Client Session Lifecycle And Results

MethodParametersReturnsDescription
inFlightFrames()Nonereadonly number[]Returns frame ids that have not reached terminal state.
completeEvent(event)event: NnrpRuntimeEventvoidApplies terminal bookkeeping for an externally consumed event.
nextResult(options?)options?: NnrpEventPollOptionsPromise<NnrpResult>Skips non-result events and returns the next terminal result.
migrate(request)request: NnrpSessionMigrationRequestPromise<void>Requests session migration; unsupported runtimes return a typed diagnostic.
patch(request)request: NnrpSessionPatchRequestPromise<NnrpSessionPatchResult>Applies mutable session metadata, profile, cadence, quality, or credits.
events(options?)options?: NnrpEventPollOptionsAsyncIterable<NnrpClientEvent>Iterates events until the session closes or polling fails.
recoveryTicket()NoneNnrpSessionRecoveryTicket | undefinedReturns the latest runtime-issued ticket snapshot when resume was negotiated.
close()NonePromise<void>Closes the role session and releases its in-flight state.

Runtime Differences

AreaNative clientBrowser client
Package@nnrp/native-client@nnrp/browser-client
Runtime openopenNativeClient(options) returns a connected client.openBrowserRuntime(options) returns a runtime, then runtime.connect(options) returns a client.
Transport packagesTCP, QUIC, IPC, and WebSocket packages carry native transport artifacts.Browser clients use the WebSocket provider with browser-client WASM.
Server APIsNot exposed.Not exposed.

Option Types

NnrpNativeClientOptions

FieldTypeRequiredDescription
endpointstring | URLYesRemote NNRP endpoint.
providerRoutesNnrpClientProviderRoutesNoPer-carrier locator and peer-verification configuration.
transportPolicyNnrpTransportPolicyNoauto, prefer-*, or force-* selection policy.
transportsreadonly NnrpNativeTransportProvider[]NoInstalled native transport providers. See Transport Providers.
sessionDefaultsNnrpSessionOptionsNoDefaults applied when sessions omit values.
ffiNnrpNativeFfiBindingNoExplicit native binding for controlled integration and tests.

NnrpBrowserRuntimeOptions

FieldTypeRequiredDescription
moduleUrlstring | URLNoExplicit WASM module URL.
moduleWebAssembly.ModuleNoPrecompiled WASM module.
artifactNnrpWasmArtifactOptionsNoBrowser WASM primitive manifest plus optional base URL.
transportPolicyNnrpTransportPolicyNoBrowser transport selection policy.
transportProvidersreadonly NnrpBrowserTransportProvider[]NoBrowser transport providers. The current SDK accepts WebSocket providers. See Transport Providers.

NnrpBrowserConnectOptions

FieldTypeRequiredDescription
endpointstringYesRemote nnrp:// or nnrps:// application endpoint.
providerRoutesNnrpClientProviderRoutesNoWebSocket route; browser trust remains host-owned.
transportPolicyNnrpTransportPolicyNoSelection policy.
transportProvidersreadonly NnrpBrowserTransportProvider[]NoBrowser providers for this connection.
sessionDefaultsNnrpBrowserSessionOptionsNoDefaults applied when sessions omit values.

NnrpSessionPriorityClass

MemberWire valueMeaning
Interactive0Latency-sensitive work that should be scheduled first.
Balanced1Default scheduling class for ordinary interactive workloads.
Background2Throughput-oriented work that may yield to interactive traffic.

NnrpSessionOptions

FieldTypeDefaultDescription
requestedSessionIdnumber0Preferred wire session id; zero lets the server assign it.
profileIdnumberstandard token profileRequested profile registry id.
schemaIdnumbertoken-delta schema idRequested schema registry id.
schemaVersionnumbertoken-delta schema versionRequested schema version.
priorityClassNnrpSessionPriorityClassBalancedRequested scheduling class.
defaultDeadlineMillisnumber500Default operation deadline.
maxInFlightOperationsnumber4Requested session concurrency ceiling.
leaseTtlHintMillisnumber30000Requested cache lease lifetime.
allowResumebooleanfalseEnables resumable-session negotiation.
resumeTokenBytesnumber0Maximum opaque recovery-token bytes accepted locally; zero uses runtime default.
cacheHintsreadonly NnrpCacheObjectKind[][]Connection capability hints folded into automatic CLIENT_HELLO.

All numeric fields are range-checked against their frozen wire widths. Handles, generations, authentication lengths, extension lengths, and client tags are derived or internal and are not public options. Cadence, quality tier, application metadata, submit-capacity policy, and local credit updates belong to profile, patch, or flow-control APIs rather than SESSION_OPEN.

NnrpBrowserSessionOptions

Same shape and defaults as NnrpSessionOptions, scoped to browser clients. The browser host owns the WebSocket carrier while Rust WASM owns handshake, multiplexed session, resume, and recovery-ticket semantics.

NnrpEventPollOptions

FieldTypeRequiredDescription
timeoutMillisnumberNoMaximum event wait in milliseconds.
signalNnrpAbortSignalLikeNoCancels the pending event wait.

NNRP Documentation